参考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\n", getpid());
- printf("%% ");
- while (fgets(buf, MAXLINE, stdin) != NULL)
- {
- if (buf[strlen(buf) - 1] == ‘\n‘)
- buf[strlen(buf)-1] = 0;
- pid = fork();
- if (pid < 0)
- {
- printf("parent: fork() error!\n");
- }
- else if (pid == 0)
- {
- printf("child: new process start!\n");
- printf("child: new process pid=%d\n", getpid());
- execlp(buf, buf, (char *)0);
- printf("child: couldn‘t execure: %s\n", buf);
- exit(1);
- }
- else
- {
- printf("parent: child process pid=%d\n", pid);
- }
- if ((pid = waitpid(pid, &status, 0)) < 0)
- printf("waitpid error\n");
- 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
- %