Unix系统中有三个进程控制的主要函数:fork、exec(有六种变体)、waitpid。下面是书中一个类似shell程序的淡化实现:
#include "apue.h"#include <sys/wait.h>
int main(void)
{
char buf[MAXLINE];
pid_t pid;
int status;
printf("%% "); //printf requires %% to print %
while (fgets(buf, MAXLINE, stdin) != NULL)
{
if (buf[strlen(buf) - 1] == '\n')
{
buf[strlen(buf) - 1] = 0; //replace newline with null
}
if ((pid = fork()) < 0)
{
err_sys("fork error");
} else if (pid == 0) // child
{
execlp(buf, buf, (char *)0);
err_ret("couldn't execute: %s", buf);
exit(127);
}
// parent
if ((pid = waitpid(pid, &state, 0)) <0)
{
err_sys("waitpid error");
}
printf("%% ");
}
exit(0);
}
gcc test.c -o test
./test
输入data、who、ls、pwd等