我在ubuntu下使用exec()函数有问题。是否有可能回到主程序?
例:
printf("Some instructions at beginningn");
execlp("ls","ls", "-l", NULL);
// i want to continue this program after exec and see the text below
printf("Other instructionsn");
No. 成功的exec
调用会将当前程序替换为另一个程序。 如果你想让父母和孩子都留下来,你需要在exec
之前打电话给fork(2)
:
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
返回,则始终是因为错误,因此请准备好处理错误。
exec
替换可执行文件映像。没有退路。一个不错的选择是 vfork() exec
. vfork
复制进程,继续复制,当它完成执行时,继续主进程。副本可以exec
所需的文件。例:
printf("Some instructions at beginningn");
if(!vfork()){
// child
execlp("ls","ls", "-l", NULL); // child is replaced
}
// parent continues after child is gone
printf("Other instructionsn");
不,无法使用 exec 系列函数,因为从您以前的代码生成的可执行文件,即包含 execlp("ls","ls","-l",NULL) 函数的代码,被您将要由 execlp() 函数运行的可执行文件(即 ls)。因此,当此函数成功执行时,您将不再拥有包含execlp()函数的旧可执行文件。
使用系统("ls -l"); 函数,如果要运行任何其他进程并想返回到当前进程。
No.exec
系列函数将当前进程替换为新的进程映像。如果您不想这样做,则需要在调用exec
之前fork
,以便替换进程的新分叉副本(而不是替换原始副本)。
实际上exec()
或其函数系列替换当前进程并执行
因此,请尝试在子进程中使用 fork 并使用exec()
,并在父进程中等待直到子进程终止。
喜欢这个:
if(!fork())
{
// In child
execlp("ls","ls","-l",NULL);
}
wait(NULL);
// In parent
//rest of code
exec
将当前进程映像替换为新的进程映像,因此,不,这是不可能的。
如果你想回到你以前做的事情,你可以做一个分叉,从子进程调用一个exec。
if (fork() == 0){ //this part will only be executed by the child process
execlp("ls","ls", "-l", NULL);
wait((int*)0);
}