首页 > 解决方案 > exec() 在这个程序中做了什么?它会停止运行吗?

问题描述

int main(void){
char *argv[3] = {"Command-line","-1", NULL};
int i;
int pid = fork();
if(pid == 0){
   for(int i=0;i<2;i++){
      execvp("ls", argv);
      fork();
      printf("%d\n",i);
    }
    printf("One\n");
  }
printf("Two\n");
return 0;
}

execvp 在这个程序中做了什么?子进程在此 execvp 调用之后是否继续运行,还是在此停止并且只有父进程继续运行?

另一个问题是,所有的 exec 调用都做同样的事情,但参数不同吗?

标签: coperating-systemsystem-calls

解决方案


以下建议的代码:

  1. 干净地编译
  2. 执行所需的功能
  3. 正确处理错误

现在建议的代码:

#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <stdio.h>


int main(void)
{
    char *args[] = { "ls", NULL };
    int pid = fork();
    switch(pid)
    {
        case 0:
            execvp("ls", args);
            perror( "execvp failed" );
            exit( EXIT_FAILURE );
            break;
            
        case -1:
            perror( "fork failed" );
            exit( EXIT_FAILURE );
            break;
            
        default:
            waitpid( pid, NULL, 0 );
            break;
    }
    return 0;
}

输出的部分列表(当没有错误发生时)是:

...
untitled
untitled1.c
untitled1.o
untitled2
untitled2.c
untitled2.o
untitled.c
untitled.c~
untitled.html
untitled.mak
untitled.o
untitled.s
untitled.txt
...

推荐阅读