簡體   English   中英

在C中使用函數execlp()

[英]Use of function execlp() in C

我正在嘗試使用函數execlp()來使子進程運行我編寫的特定代碼,但我不了解路徑的工作方式。

注意:我使用export PATH=$PATH:. 在終端中,因此我不需要每次都鍵入/.ProgName

第一個程序是:

#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());
    }

}

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");

}

這兩個程序位於同一目錄中。 第二個程序名為“ exectest”,但是當我啟動第一個程序時,會收到錯誤消息。

由於第一個程序啟動可執行文件exectest ,因此應編譯第二個文件exectest.c並獲取名為exectest可執行文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM