您的位置:首页 > 编程语言

一个创建子进程的简单示例代码

2014-01-16 00:56 483 查看
参考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
%
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c语言 fork exec