main.c

来自「linux中管道的使用示例」· C语言 代码 · 共 91 行

C
91
字号
#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <error.h>#include <sys/types.h>int main(int argc, char **argv){    int fd_pipe[2] = {-1};    pid_t iChildProcessID = 0;    char szReadPipeBuffer[200] = {0};    char szCommandLineBuffer[200] = {0};    char *pszCommandLineBuffer = NULL;    if(argc == 1)    {        printf("Please input command:");        if((pszCommandLineBuffer = gets(szCommandLineBuffer)) == NULL)        {            perror("gets");            return EXIT_FAILURE;        }    }    else    {        pszCommandLineBuffer = argv[1];    }    if(pipe(fd_pipe) < 0)    {        perror("pipe()");    }    else    {        iChildProcessID = fork();        if(iChildProcessID < 0)        {            perror("fork()");        }        else if(iChildProcessID == 0)        {             close(fd_pipe[1]);             fd_pipe[1] = -1;             sleep(1);             printf("In child process.\n");                          int iRet = read(fd_pipe[0],szReadPipeBuffer,200);             if(iRet)             {                 printf("Executing \"%s\" ...\n",szReadPipeBuffer);                 system(szReadPipeBuffer);                 close(fd_pipe[0]);                 fd_pipe[0] = -1;             }             else             {                 perror("read from pipe.");             }        }        else        {             close(fd_pipe[0]);             fd_pipe[0] = -1;             //int iRet = write(fd_pipe[1],argv[1],strlen(argv[1]));                  int iRet = write(fd_pipe[1],pszCommandLineBuffer,strlen(pszCommandLineBuffer));                  if(iRet < 0)             {                 perror("write to pipe.");             }                         sleep(2);             iChildProcessID = wait(NULL);             close(fd_pipe[1]);             fd_pipe[1] = -1;        }//if(fork())    }//if(pipe(fd_pipe)).../*    close(fd_pipe[0]);    fd_pipe[0] = -1;    close(fd_pipe[1]);    fd_pipe[1] = -1;*/    return EXIT_SUCCESS;}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?