5

我在 ubuntu 下的 exec() 函数有问题。有没有可能回到主程序?

例子:

printf("Some instructions at beginning\n");
execlp("ls","ls", "-l", NULL);

// i want to continue this program after exec and see the text below
printf("Other instructions\n");
4

6 回答 6

6

不会。成功的exec调用会用另一个程序替换当前程序。如果您希望父母和孩子都留下来,您需要在fork(2)之前调用exec

pid_t childpid = fork();
if(childpid < 0)
{
    // Handle error
}
else if(childpid == 0)
{
    // We are the child
    exec(...);
}
else
{
    // We are the parent: interact with the child, wait for it, etc.
}

请注意,失败的exec调用(例如,给定的可执行文件不存在)会返回。如果exec返回,总是因为错误,所以要准备好处理错误。

于 2012-11-24T19:49:53.127 回答
2

exec替换可执行文件映像。没有退路。一个不错的选择是vfork() exec. vfork复制流程,继续复制,当它完成执行时,继续主流程。副本可以exec是所需的文件。例子:

printf("Some instructions at beginning\n");
if(!vfork()){
    // child
    execlp("ls","ls", "-l", NULL); // child is replaced
}
// parent continues after child is gone
printf("Other instructions\n");
于 2012-11-24T19:51:49.057 回答
2

不,不可能使用 exec 系列函数,因为由您以前的代码生成的可执行文件,即包含execlp("ls","ls","-l",NULL) 函数的代码,被您的可执行文件替换将由execlp()函数运行,即ls。因此,当此函数成功执行时,您将不再拥有包含execlp()函数的旧可执行文件。

Use system("ls -l"); function if you want to run any other process and want to return to current process.

于 2015-08-20T15:34:07.120 回答
1

exec 用新的过程映像替换当前的过程映像,所以,,这是不可能的。

如果您想恢复之前所做的事情,您可以执行 fork 并从子进程中调用 exec。

if (fork() == 0){ //this part will only be executed by the child process
        execlp("ls","ls", "-l", NULL);
        wait((int*)0);
}
于 2012-11-24T19:49:38.343 回答
1

不会exec。函数族用新的过程映像替换当前过程。如果您不想这样做,则需要fork在调用之前执行此操作exec,以便替换进程的新分叉副本(而不是替换原始副本)。

于 2012-11-24T19:50:29.473 回答
0

实际上exec()或者它的函数族替换当前进程并执行

所以尝试exec()在子进程中分叉和使用,并在父进程中等待子进程终止。

像这样 :

if(!fork())
 {
  // In child
  execlp("ls","ls","-l",NULL);
 }
 wait(NULL);
  // In parent 
 //rest of code
于 2012-11-24T19:50:47.267 回答