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");
いいえ。exec
呼び出しが成功すると、現在のプログラムが別のプログラムに置き換えられます。親と子の両方を固定したい場合は、fork(2)
beforeを呼び出す必要があります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
は、常にエラーが原因であるため、エラーを処理する準備をしてください。
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");
いいえ。exec
関数ファミリーは、現在のプロセスを新しいプロセス イメージに置き換えます。それをしたくない場合は、 をfork
呼び出す前に行う必要がありますexec
。これにより、プロセスの新しくフォークされたコピーが (元のプロセスが置き換えられるのではなく) 置き換えられます。
exec
現在のプロセス イメージを新しいプロセス イメージに置き換えるため、いいえ、それは不可能です。
以前行っていたことに戻りたい場合は、fork を実行して、子プロセスから exec を呼び出すことができます。
if (fork() == 0){ //this part will only be executed by the child process
execlp("ls","ls", "-l", NULL);
wait((int*)0);
}
実際exec()
に、またはその関数のファミリーは、現在のプロセスを置き換えて実行します
そのため、フォークしexec()
て子プロセスで使用し、子が終了するまで親で待機します。
このような :
if(!fork())
{
// In child
execlp("ls","ls","-l",NULL);
}
wait(NULL);
// In parent
//rest of code