linux 编程使用管道来控制 shell

本文介绍了一个使用Linux管道实现前后台进程间通信的C程序示例。该程序演示了如何从前台接收用户输入并将其传递给后台的shell进程,再将shell进程的执行结果返回给前台显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  这个程序的作用就是 前台输入的 数据通过管道传递给后台的 sh 进程 然后将执行的结果返回到前台  

   linux 的管道使用要注意  一个管道 只能一端读 一端 写  当创建完子进程后   父进程和子进程都需要关闭管道的一端  因为 没必要自己写 自己读  此处  需要使用两个管道 

#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>

int read_pipe[2];
int write_pipe[2];

void MyCreateThread(void *(*func)(void *),void *lparam)
{
    pthread_attr_t attr;
    pthread_t  p;
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
    pthread_create(&p,&attr,func,lparam);
    pthread_attr_destroy(&attr);
}

void *read_thread(void *lparam)
{
    char cmd[100];
    int bytes = 0;
    while((bytes = read(STDIN_FILENO,cmd,100)) > 0)
    {
        write(write_pipe[1],cmd,bytes);
    }
    return NULL;
}

int main(int argc, char *argv[])
{
    int pid;
    pipe(read_pipe);
    pipe(write_pipe);
    pid = fork();

    if(0 == pid)
    {
        //进入子进程
        //  启动 shell 进程
        close(read_pipe[0]);
        close(write_pipe[1]);
        char *argv[] = {"/bin/sh",NULL};
        char *shell = "/bin/sh";
        dup2(write_pipe[0],STDIN_FILENO); //将输入输出重定向到管道
        dup2(read_pipe[1],STDOUT_FILENO);
        dup2(read_pipe[1],STDERR_FILENO);
        execv(shell,argv);
    }
    else
    {
        char buff;

        close(read_pipe[1]);
        close(write_pipe[0]);
        printf("child process id %d \n",pid);
        write(write_pipe[1],"ls\n",3);
        //启动一个线程来读取
        MyCreateThread(read_thread,NULL);

        while(read(read_pipe[0],&buff,1) > 0)
        {
            putchar(buff);
        }
        waitpid(pid,NULL,0);
        printf("child exit. ..\n");
    }
    return 0;
}

转载于:https://my.oschina.net/sincoder/blog/123465

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值