【发布时间】:2012-04-02 17:31:25
【问题描述】:
我这里有一个例子:
int runcmd(char *cmd)
{
char* argv[MAX_ARGS];
pid_t child_pid;
int child_status;
parsecmd(cmd,argv);
child_pid = fork();
if(child_pid == 0) {
/* This is done by the child process. */
execvp(argv[0], argv);
/* If execvp returns, it must have failed. */
printf("Unknown command\n");
exit(0);
}
else {
/* This is run by the parent. Wait for the child
to terminate. */
do {
pid_t tpid = wait(&child_status);
if(tpid != child_pid) process_terminated(tpid);
} while(tpid != child_pid);
return child_status;
}
}
这是一个经典的fork()例子 在 fork() 之后,控制权转到子进程。 我怎样才能保留在父进程中,做一些事情。而不是立即跳到孩子身上?
谢谢
【问题讨论】:
-
我想你误会了。
fork()返回子进程和父进程。if部分在子进程中执行,else部分在父进程中运行。