exec 如何在 Linux 上工作
How exec works on Linux
我试图了解 exec 的工作原理,但现在我被困在这个例子上了。在不删除提供的文本中的任何内容的情况下,编辑以下函数,以便程序将命令应用于接收到的所有参数,这是如何完成的?谢谢! :)
int main(int argc, char** argv[]){
for(int i=1; i<argc; i++){
execlp("cat", "cat", argv[i]);
printf("Error\n");
exit(1);
}
return 0;
}
execlp() 将替换当前进程。
注意:execlp()
的最后一个参数必须为 NULL
为避免当前进程被覆盖,第一步是调用fork()
创建子进程。
自然地允许 fork() 的每个可能返回值`
那么父进程需要等待子进程退出
否则多个子进程,每个 运行 cat
,将竞相在终端上显示它们的输出。
因此父进程需要等待每个子进程完成后再创建下一个子进程
应用以上所有结果:
#include <sys/types.h>
#include <sys/wait.h> // waitpid()
#include <unistd.h> // fork()
#include <stdio.h> // perror()
#include <stdlib.h> // exit(), EXIT_FAILURE
int main(int argc, char* argv[]) // single `*` when using `[]`
{
pid_t pid;
for(int i=1; i<argc; i++)
{
switch( pid = fork() )
{
case -1:
// handle error
perror( "fork failed");
exit( EXIT_FAILURE );
break;
case 0: // the child
execlp("cat", "cat", argv[i], NULL);
perror("execlp failed");
exit( EXIT_FAILURE );
break;
default:
// parent
// wait for child to exit
waitpid( pid, NULL, 0);
break;
} // end switch
} // end for
return 0;
} // end function: main
我试图了解 exec 的工作原理,但现在我被困在这个例子上了。在不删除提供的文本中的任何内容的情况下,编辑以下函数,以便程序将命令应用于接收到的所有参数,这是如何完成的?谢谢! :)
int main(int argc, char** argv[]){
for(int i=1; i<argc; i++){
execlp("cat", "cat", argv[i]);
printf("Error\n");
exit(1);
}
return 0;
}
execlp() 将替换当前进程。
注意:execlp()
的最后一个参数必须为 NULL
为避免当前进程被覆盖,第一步是调用fork()
创建子进程。
自然地允许 fork() 的每个可能返回值`
那么父进程需要等待子进程退出
否则多个子进程,每个 运行 cat
,将竞相在终端上显示它们的输出。
因此父进程需要等待每个子进程完成后再创建下一个子进程
应用以上所有结果:
#include <sys/types.h>
#include <sys/wait.h> // waitpid()
#include <unistd.h> // fork()
#include <stdio.h> // perror()
#include <stdlib.h> // exit(), EXIT_FAILURE
int main(int argc, char* argv[]) // single `*` when using `[]`
{
pid_t pid;
for(int i=1; i<argc; i++)
{
switch( pid = fork() )
{
case -1:
// handle error
perror( "fork failed");
exit( EXIT_FAILURE );
break;
case 0: // the child
execlp("cat", "cat", argv[i], NULL);
perror("execlp failed");
exit( EXIT_FAILURE );
break;
default:
// parent
// wait for child to exit
waitpid( pid, NULL, 0);
break;
} // end switch
} // end for
return 0;
} // end function: main