execlp() 系统调用如何工作? [英] how does execlp() system call work?

查看:66
本文介绍了execlp() 系统调用如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

int main(){
pid_t pid;
pid = fork();
if(pid<0){
   fprintf(stderr, "fork failed");
   return 1;    }
else if(pid == 0){  
   execlp("bin/ls", "ls", NULL);}
else{
   wait(NULL);
   printf("child complete\n");
   }
return 0;
}

据我所知,这里创建了一个子进程,由于fork返回的pid为0",它进入包含execlp的块并执行它,然后父进程等待子进程退出,然后打印孩子完成".如果我错了,请纠正我.但我不明白 execlp() 在这里是如何工作的.有人能解释一下吗?

Here as far as I could understand, a child process is created and since its pid returned by fork is "0", it enters the block containing execlp and executes it, and then the parent waits till the child exits and then prints "child complete". Please correct me if I'm wrong. But I didnt understand how execlp() works here. Can someone explain this?

推荐答案

fork 创建一个新进程,它被父进程调用一次,但在父进程和子进程中返回两次.

fork creates a new process, it is called once by the parent but returns twice in the parent and in the child.

在子进程中调用execlp执行指定的命令ls.

In the child process the call execlp executes the specified command ls.

这会用新的程序文件(ls 程序文件)替换子进程,这意味着以下.

This replaces the child process with the new program file (ls program file) which means following.

当一个进程调用 execlp 或其他 7 个 exec 函数之一时,该进程被新程序完全取代,新程序开始执行主要的功能.

When a process calls the execlp or one of the other 7 exec functions, that process is completely replaced by the new program, and the new program starts executing at its main function.

进程 ID 在 exec 中不会改变,因为新进程不是创建.exec 仅仅替换当前进程的文本、数据、堆和栈用磁盘中的全新程序分段.

The process ID does not change across an exec, because a new process is not created. exec merely replaces the current process's text, data, heap, and stack segments with a brand new program from disk.

fork 后跟 exec 的组合在某些操作系统上称为 spawning a new process.

The combination of fork followed by exec is called spawning a new process on some operating systems.

希望它或多或少地清楚.如果您有更多问题,请告诉我.

Hopefully it was more or less clear. Let me know if you have more questions.

这篇关于execlp() 系统调用如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆