此程序等同于在linux下运行ps -A命令,popen函数正是用这种方式实现的。
程序代码:
#include
#include
#include
#include
#include
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