【发布时间】:2014-09-21 07:03:55
【问题描述】:
我有一个程序应该启动另一个进程并与之同时工作。我正在使用fork() 和system() 来完成此操作。我有代码验证我的system() 调用是否返回,但每次执行时我都必须通过键入ctrl c 手动结束执行。我可以说我的一个进程终止了,但我不太确定是哪一个。我相信是父母。两者都应该被 return 语句捕获。
这里是父进程代码(forkWaitTest):
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
int main(void)
{
pid_t childPID;
int status;
childPID = fork();
if(childPID >=0)
{
if(childPID == 0)
{
cout <<"I'm the fork child";
cout.flush();
status=system("child");
cout << "status = " << status;
//exit(0);
//cout << "Am I getting here?";
}
else{
cout << "I am the parent and can keep doing things ";
int y=1;
int x=7;
cout<< y+x << " ";
}
}
return 0;
}
这是被调用的子进程
#include <stdio.h>
int main(int argc, char *argv[] )
{
printf("I am the child\n");
return 0;
}
这是我的输出:
-bash-4.2$ forkWaitTest
I am the parent and can keep doing things 8 I'm the fork child-bash-4.2$ I am the child
status = 0
【问题讨论】:
-
您如何确定某事“永不终止”?
-
我必须推动
ctrl c才能结束 -
你的父母应该为孩子
wait()ing,虽然我不能立即明白为什么不这样做会导致这种行为。 -
我希望父进程与
system调用的子进程同时运行。最终我不得不把它变成我课程的客户端服务器程序。一个要求是我的客户启动我的服务器