2017-10-21 58 views
0

terminal code(Unix/Linux)如何從另一個需要輸入文件的C程序執行C程序?

在上圖中,代碼可以簡單地從終端運行。運行pipeclient和pipeserver文件。 pipeclient文件將command.txt作爲輸入使用<符號。

現在,如果我不想從終端運行pipeclient文件,但想從C程序運行,我該怎麼辦呢? exec功能集幫助我嗎?我如何使用C程序中的command.txt輸入文件運行pipeclient文件?

+1

在linux上你可以使用popen() – technosaurus

回答

2

低從文件中獲取輸入來運行程序的級別方式爲:

  • 打開文件使用open
  • 使用dup2系統調用在手柄的標準輸入的頂部複製打開的文件句柄讀取(總是處理0
  • close老手柄(副本複製在手柄0頂部將保持打開)
  • 使用execve或其它功能從exec家庭切換到新方案,該方案現在將有它的標準輸入打開該文件。

這與殼本身實現< file輸入重定向的方式相同。

下面是在當前目錄中使用來自commands.txt文件輸入運行/usr/bin/rev一個例子:

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

extern char **environ; 

#define ERROR(msg) do { perror(msg); exit(1); } while(0) 

int main() 
{ 
    // open the input file 
    int fd = open("commands.txt", O_RDONLY); 
    if (fd == -1) 
     ERROR("open"); 

    // "dup" the handle to standard input (handle 0) 
    if (dup2(fd, 0) == -1) 
     ERROR("dup2"); 

    // close the old handle 
    close(fd); 

    // exec the program 
    char *args[] = {"rev", NULL}; 
    execve("/usr/bin/rev", args, environ); 

    // the program never gets here, unless the exec fails 
    ERROR("execve"); 
    return -1; 
} 

您還可以使用system命令,執行包括重定向shell命令,所以程序:

#include <stdio.h> 
#include <stdlib.h> 

#define ERROR(msg) do { perror(msg); exit(1); } while(0) 

int main() 
{ 
    if (system("/usr/bin/rev <commands.txt")) 
     ERROR("system"); 

    // this *will* return after completion 
    return 0; 
} 

也可以工作。在這裏,system調用實際上是調用一個shell(「/ bin/sh」)的副本來處理命令行,就像它是一個shell命令一樣。

這樣更方便,但對調用子程序的過程(例如,設置其環境,清除其參數列表等)的控制較少。使用system也存在複雜的潛在安全問題,如果您的程序將以root運行,那麼這可能會成爲問題,但這可能不是問題。

0

您可以使用system函數來調用你的第二個方案,第一個çprogram.like

1st.c

#include <stdio.h> 
#include<ctype.h> 
#include <stdlib.h> 
int main() 
{ 
    printf("I m 1st program"); 
    system("./2nd.out\n"); 
} 

2nd.c

#include <stdio.h> 
#include<ctype.h> 
#include <stdlib.h> 


int main(int argc, char **argv) 
{ 
     printf("Hello there i m 2nd program\n") 

}