Ahm*_*kin 3 c++ linux fork execv
我是C++上的新手,并在Linux上开发一个简单的程序,该程序应该调用同一目录中的另一个程序并获取被调用程序的输出,而不显示调用程序上调用程序的输出.这是我正在处理的代码片段:
pid_t pid;
cout<<"General sentance:"<<endl<<sentence<<endl;
cout<<"==============================="<<endl;
//int i=system("./Satzoo");
if(pid=fork()<0)
cout<<"Process could not be created..."<<endl;
else
{
cout<<pid<<endl;
execv("./Satzoo",NULL);
}
cout<<"General sentance:"<<endl<<sentence<<endl;
cout<<"==============================="<<endl;
Run Code Online (Sandbox Code Playgroud)
我遇到的一个问题是我能够在控制台上打印前两行,但我不能打印最后两行.我认为当我调用Satzoo程序时程序停止工作.另一件事是这个代码调用Satzoo程序两次,我不知道为什么?我可以在屏幕上看到输出两次.另一方面,如果我使用system()而不是execv(),那么Satzoo只能使用一次.
我还没想出如何在我的程序中读取Satzoo的输出.
任何帮助表示赞赏.
谢谢
Bob*_*toe 12
在调用之后,您无法区分子进程和父进程fork().因此,孩子和父母都跑execv(),因此他们各自的过程图像被替换.
你想要更像的东西:
pid_t pid;
printf("before fork\n");
if((pid = fork()) < 0)
{
printf("an error occurred while forking\n");
}
else if(pid == 0)
{
/* this is the child */
printf("the child's pid is: %d\n", getpid());
execv("./Satzoo",NULL);
printf("if this line is printed then execv failed\n");
}
else
{
/* this is the parent */
printf("parent continues execution\n");
}
Run Code Online (Sandbox Code Playgroud)