linux下通过dup2标准输出重定向查看系统进程方法(也是popen函数实现的方法)

此程序等同于在linux下运行ps -A命令,popen函数正是用这种方式实现的。

 

程序代码:

 

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>


int mysystem(char* cmdstring, char* buf, int len)
{
      int   fd[2];
      pid_t pid;
      int   n, count;
       memset(buf, 0, len);
      if (pipe(fd) < 0)
          return -1;
      if ((pid = fork()) < 0)
          return -1;
      else if (pid > 0)     /* parent process */
      {         close(fd[1]);     /* close write end */
                 count = 0;
                 while ((n = read(fd[0], buf + count, len)) > 0 && count > len)
                        count += n;
                 close(fd[0]);
                 if (waitpid(pid, NULL, 0) > 0)
                        return -1;
      }
      else                  /* child process */
      {          close(fd[0]);     /* close read end */
                 if (fd[1] != STDOUT_FILENO)
                 {
                        if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
                        {                  return -1;
                        }
                        close(fd[1]);
                }
                if (execl("/bin/sh", "sh", "-c", cmdstring, (char*)0) == -1)
                        return -1;
      }
      return 0;
  }


int main(int argc, char *argv[])
{
         char buf[8192];
         char *cmd="ps -A";
         mysystem(cmd,buf,8192);

         printf("%s", buf);
         return 0;
}

运行:

[root@localhost ~]# ./mysystem
  PID TTY          TIME CMD
    1 ?        00:00:00 init
    2 ?        00:00:00 migration/0
    3 ?        00:00:00 ksoftirqd/0
    4 ?        00:00:00 watchdog/0
    5 ?        00:00:00 events/0
    6 ?        00:00:00 khelper
    7 ?        00:00:00 kthread
   10 ?        00:00:00 kblockd/0
   11 ?        00:00:00 kacpid
   72 ?        00:00:00 cqueue/0
   75 ?        00:00:00 khubd
   77 ?        00:00:00 kseriod
  135 ?        00:00:00 pdflush
  136 ?        00:00:00 pdflush
  137 ?        00:00:00 kswapd0
  138 ?        00:00:00 aio/0
  286 ?        00:00:00 kpsmoused
  316 ?        00:00:00 scsi_eh_0
  321 ?        00:00:00 kmirrord
  328 ?        00:00:00 kjournald
  349 ?        00:00:00 kauditd
  375 ?        00:00:00 udevd
  710 ?        00:00:00 kgameportd
 1266 ?        00:00:00 kmpathd/0
 1289 ?        00:00:00 kjournald
 1295 ?        00:00:00 vmhgfs
 1297 ?        00:00:00 kjournald

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值