简体   繁体   English

在C中使用函数execlp()

[英]Use of function execlp() in C

I'm trying to use the function execlp() to make a child processes run a specific code that I wrote, but I don't understand how the path works. 我正在尝试使用函数execlp()来使子进程运行我编写的特定代码,但我不了解路径的工作方式。

NOTE: I use export PATH=$PATH:. 注意:我使用export PATH=$PATH:. in the terminal so I don't need to type /.ProgName every time. 在终端中,因此我不需要每次都键入/.ProgName

The first program is: 第一个程序是:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
main() {

    pid_t childpid; 
    int i;
    int nprocess = 3;
    for (i = 0; i < nprocess; ++i) {
     if ((childpid = fork()) < 0) {
         perror("fork:");
         exit(1);
     } 
     if (childpid==0){ 
        printf("I'm the son with ID= %ld\n",(long)getpid());
        char *path = "exectest";
        if ((execl(path,"0",NULL))<0) printf("\n error exec \n");
    } 
      else 
        printf("I'm the father with ID= %ld",(long)getpid());
    }

}

The second program to be called by the execlp is : execlp调用的第二个程序是:

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


void main(){


        printf("\n I'm using exec \n");

}

Both programs are in the same directory. 这两个程序位于同一目录中。 The second program is named "exectest" but when I launch the first, I get the error message. 第二个程序名为“ exectest”,但是当我启动第一个程序时,会收到错误消息。

由于第一个程序启动可执行文件exectest ,因此应编译第二个文件exectest.c并获取名为exectest可执行文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM