创建子进程来运行 ls -l 程序

创建子进程来运行 ls -l 程序

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/wait.h>
int main(void)
{
    pid_t childpid;
    childpid= fork();
    if(childpid==-1){
     perror("Failed to fork");
     return 1;

    }
      if (childpid== 0){
         execl("/bin/ls","ls","-l","/home/chujiangke");
         perror("Child failed to exec ls");
         return 1;
      }
      if(childpid != wait(NULL))
      {
         perror("Parent failed to wait due to signal or error");
         return 1;
      }
      return 0;
}


您好,这是一个经典的管道问题。在Linux,可以使用pipe函数来创建一个管道,使用fork函数来创建一个子进程。父进程可以将命令的输出写入管道,子进程可以从管道读取命令的输出并进行处理。 下面是示例代码: ```c #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/wait.h> #define BUFFER_SIZE 1024 int main() { int pipefd[2]; pid_t pid; char buf[BUFFER_SIZE]; int status; // 创建管道 if (pipe(pipefd) == -1) { perror("pipe"); exit(EXIT_FAILURE); } // 创建子进程 pid = fork(); if (pid == -1) { perror("fork"); exit(EXIT_FAILURE); } if (pid == 0) { // 子进程 // 关闭写端 close(pipefd[1]); // 从管道读取命令的输出 while (read(pipefd[0], buf, BUFFER_SIZE) > 0) { // 进行筛选操作 if (strstr(buf, "7-5") != NULL) { printf("Found: %s", buf); } } // 关闭读端 close(pipefd[0]); _exit(EXIT_SUCCESS); } else { // 父进程 // 关闭读端 close(pipefd[0]); // 将命令的输出写入管道 FILE* fp = popen("ls -l", "r"); if (fp == NULL) { perror("popen"); exit(EXIT_FAILURE); } while (fgets(buf, BUFFER_SIZE, fp) != NULL) { if (write(pipefd[1], buf, strlen(buf)) == -1) { perror("write"); } } // 关闭写端 close(pipefd[1]); // 等待子进程结束 wait(&status); if (WIFEXITED(status)) { printf("Child exited with status %d\n", WEXITSTATUS(status)); } else { printf("Child terminated abnormally\n"); } } return 0; } ``` 在上面的示例代码,首先使用pipe函数创建一个管道,然后使用fork函数创建一个子进程。在子进程,关闭写端,从管道读取命令的输出,并进行筛选操作;在父进程,关闭读端,将命令的输出写入管道,等待子进程结束。 注意:在示例代码,我使用了popen函数来执行ls -l”命令,并将输出写入管道。popen函数会创建一个管道,并使用fork函数创建一个子进程执行命令。如果您不想使用popen函数,可以将它替换为其他方法来执行命令并将输出写入管道。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值