今天嘗試《UNIX環境高級編程》的例1-5,代碼如下:
#include <sys/types.h>
#include <sys/wait.h>
#include "ourhdr.h"
int main(void)
{
char buf[MAXLINE];
pid_t pid;
int status;
printf("%% "); /* print prompt (printf requires %% to print %) */
while (fgets(buf, MAXLINE, stdin) != NULL) {
buf[strlen(buf) - 1] = 0; /* replace newline with null */
if ((pid = fork()) < 0)
err_sys("fork error");
else if (pid == 0) {
execlp(buf, buf, NULL);
err_ret("couldn't execute: %s", buf);
exit(127);
}
/* parent */
if ((pid = waitpid(pid, &status, 0)) < 0)
err_sys("waitpid error");
printf("%% ");
}
exit(0);
}
ourhdr.h頭文件是附錄2裏面的內容,這個程序不能直接運行,讀者想嘗試的需要把附錄2的內容包含進來一起編譯
悲劇的是我把這一行敲成這樣了:
gcc -v出來的版本是“gcc version 4.1.1 20070105 (Red Hat 4.1.1-52)”
使用gcc 1-5.c ourhbr.c編譯沒有報任何錯就通過了,但是執行程序怎麼也打不到預期的結果:
納悶了半天,最後突然看到這行語句右邊沒有值,果斷賦值了就解決了:
粗細啊,對着巧都敲錯了,不過也好,這樣就發現gcc居然對這種不賦值的表達式居然不報錯。不知道高版本如何
個人覺得這個不利於排錯啊,尤其是我這樣的馬大哈啊