参考APUE中第1章1.6小节
主要涉及到2个函数: fork、exec
- // filename : process_ctrl.c
- // child process -- fork, exec, waitpid
- #include <stdio.h>
- #include <sys/wait.h>
- #define MAXLINE 32
- int main(int argc, char *argv[])
- {
- char buf[MAXLINE];
- pid_t pid;
- int status;
- printf("parent: pid=%d ", getpid());
- printf("%% ");
- while (fgets(buf, MAXLINE, stdin) != NULL)
- {
- if (buf[strlen(buf) - 1] == ' ')
- buf[strlen(buf)-1] = 0;
- pid = fork();
- if (pid < 0)
- {
- printf("parent: fork() error! ");
- }
- else if (pid == 0)
- {
- printf("child: new process start! ");
- printf("child: new process pid=%d ", getpid());
- execlp(buf, buf, (char *)0);
- printf("child: couldn't execure: %s ", buf);
- exit(1);
- }
- else
- {
- printf("parent: child process pid=%d ", pid);
- }
- if ((pid = waitpid(pid, &status, 0)) < 0)
- printf("waitpid error ");
- printf("%%");
- }
- }
运行结果:
- %[mht@localhost p1_5]$ ./process_ctrl
- parent: pid=6922
- % ls
- child: new process start!
- child: new process pid=6927
- process_ctrl process_ctrl.c
- parent: child process pid=6927
- %