简体   繁体   English

execvp()之后cout / stdout不起作用

[英]cout/stdout not working after execvp()

So I am attempting to use execvp() from unistd.h in a short program I'm writing. 所以我试图在我编写的一个简短程序中使用unistd.h中的execvp() However for some strange reason I seem to be losing the ability to use cout or even printf after calling the execvp function. 但是由于某些奇怪的原因,在调用execvp函数后,我似乎失去了使用cout甚至printf的功能。

For example this works: 例如,这有效:

pid_t pid;
int status;
if ((pid = fork()) > 0) {
  waitpid(pid, &status, 0);
}
else {
  execvp(argv[1], &argv[1]);
}
cout << "DONE!" << endl;

But this does not work: 但这不起作用:

execvp(argv[1], &argv[1]);
cout << "DONE!" << endl;

And, while it is not a huge problem, I would like to understand why it is happening. 而且,尽管这不是一个大问题,但我想了解为什么会这样。 I have not been able to find anything relevant when I searched here and with Google. 在这里和Google进行搜索时,我找不到任何相关的信息。

Not sure if this has anything at all to do with the issue but I am using the -std=c++11 flag with g++ . 不知道这是否与问题有任何关系,但是我在g++使用-std=c++11标志。

This will not work 这行不通

execvp(argv[1], &argv[1]);
cout << "DONE!" << endl;

Because the function execvp() never returns (if it succeeded). 因为函数execvp()从不返回(如果成功)。

It replaces the current processes with a new image and executes that. 它将当前进程替换为新映像并执行该映像。

On the other this works: 另一方面,这有效:

if ((pid = fork()) > 0) {
  waitpid(pid, &status, 0);
}
else {
  execvp(argv[1], &argv[1]);
}
cout << "DONE!" << endl;

What happens here is that fork() creates a new processes. 这里发生的是fork()创建了一个新进程。 So you now have two processes at exactly the same place. 因此,您现在在完全相同的位置拥有两个进程。

  • One processes has the variable pid set to zero (this is the parent). 一个进程将变量pid设置为零(这是父进程)。 It goes into the first branch of the if statement and there waits for the child to finish. 它进入if statement的第一个分支,并在那里等待子进程完成。
  • One processes has the variable pid set to none zero (this is the child). 一个进程将变量pid设置为none零(这是子级)。 It goes into the second branch. 它进入第二个分支。 It executes execvp() which never returns. 它执行永远不会返回的execvp() It does not return because the processes image is replaced by another executable. 它不会返回,因为进程映像已被另一个可执行文件替换。

Note what you should really do is: 请注意,您真正应该做的是:

if ((pid = fork()) > 0) {
  waitpid(pid, &status, 0);
  cout << "Child Finished!" << endl;
}
else {
  execvp(argv[1], &argv[1]);
  // This code should never execute if everything is OK.
  cout << "Child failed to start" << endl;
  exit(1);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM