c语言 fork pipe 实现popen plcose源码

21 篇文章 3 订阅
20 篇文章 11 订阅

参考popen, pclose源码进行了修改
第一次的问题已解决
如下图
1.png

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <dirent.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <sys/resource.h>

#define SHELL "/bin/bash"

pid_t *childpid = NULL;
int maxfd;

int open_max() {
	struct rlimit limit;
    if(getrlimit(RLIMIT_NOFILE,&limit) == -1) {
        perror("getrlimit");
        return -1;
    }
    return (int)limit.rlim_cur;
}

FILE *mpopen(const char* cmdstr, const char *mode) {
    int pipefd[2];
    pid_t pid;
    FILE *fp;

    if ((mode[0] != 'r' && mode[0] != 'w') || mode[1] != 0) {
        fprintf(stderr, "Only Support r or w !\n");
        return NULL;
    }
    
    if (childpid == NULL) {
        maxfd = open_max();
        if ((childpid = calloc(maxfd, sizeof(pid_t))) == NULL) return NULL;
    }

    if (pipe(pipefd) < 0) return NULL;

    if ((pid = fork()) < 0) {
        return NULL;
    }
    else if (pid == 0) {
        if (*mode == 'r') {
            close(pipefd[0]);
            if (pipefd[1] != STDOUT_FILENO) {
                dup2(pipefd[1], STDOUT_FILENO);
                close(pipefd[1]);
            }
        }
        else {
            close(pipefd[1]);
            if (pipefd[0] != STDIN_FILENO) {
                dup2(pipefd[0], STDIN_FILENO);
                close(pipefd[0]);
            }
        }
    
        for (int i = 0; i < maxfd; i++) {
            if (childpid[i]) close(i);
        }

        execl(SHELL, "sh", "-c", cmdstr, (char *)0);
    }
    
    if (*mode == 'r') {
        close(pipefd[1]);
        if ((fp = fdopen(pipefd[0], mode)) == NULL) return NULL;
    }
    else {
        close(pipefd[0]);
        if ((fp = fdopen(pipefd[1], mode)) == NULL) return NULL;
    }
    childpid[fileno(fp)] = pid;
    return fp;
}

int mpclose(FILE *fp) {
    int fd, stat;
    pid_t pid;
    
    if (childpid == NULL) return -1;

    fd = fileno(fp);

    if ((pid = childpid[fd]) == 0) return -1;
    
    waitpid(pid, &stat, 0);

    return stat;
}

int main() {
	FILE * fp;
	char buff[1024];

    //char *str = "cat /etc/passwd";
    char *str = "ls";
    //char *str = "ifconfig eth0";

    printf("cmdstr = %s\n", str);
    printf("My Popen and Pclose: \n");
    fp = mpopen(str, "r");
	fgets(buff, sizeof(buff), fp);
	printf("%s", buff, strlen(buff));
	mpclose(fp);

    printf("System Popen and Pclose: \n");
    fp = popen(str, "r");
	fgets(buff, sizeof(buff), fp);
	printf("%s", buff, strlen(buff));
	pclose(fp);
    
    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值