我是 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;
我遇到的一个问题是,我能够在控制台上打印前两行,但无法打印后两行。我认为当我调用 Satzoo 程序时该程序停止工作。 另一件事是这段代码调用了两次 Satzoo 程序,我不知道为什么?我可以在屏幕上看到两次输出。另一方面,如果我使用 system() 而不是 execv(),那么 Satzoo 只工作一次。
我还没有想出如何在我的程序中读取 Satzoo 的输出。
感谢任何帮助。
谢谢
最佳答案
调用 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");
}
关于C++ fork() 和 execv() 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1586286/