#include <unistd.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/wait.h>
int pexec(const char* command,int* result)
{
int pid;
int fds[2] = {-1,-1};
int status = -1;
if(pipe(fds) < 0)
{
return -1;
}
if( (pid=vfork()) < 0)
{
close(fds[0]);
close(fds[1]);
return -1;
}
if (pid == 0 )
{
dup2(fds[1],1);
close(fds[0]);
close(fds[1]);
execl("/bin/sh", "sh", "-c", command,NULL);
_exit(-1);
}
else
{
waitpid(pid,&status,0);
close(fds[1]);
if (WIFEXITED(status)==0)
{
close(fds[0]);
return -1;
}
status = WEXITSTATUS(status);
if (result!=NULL)
{
*result = status;
}
//printf("pid(%d) exited,status:%d \r\n",pid,status);
return fds[0];
}
}
int main(int argc,char* argv[])
{
if (argc<2)
{
printf("Usage:%s <cmd> \r\n",argv[0]);
return -1;
}
int status = -1;
int fd = pexec(argv[1],&status);
if (fd==-1)
{
printf("pexec(%s) error \r\n",argv[1]);
return -1;
}
char buf[4097];
int readed = 0;
while( (readed = read(fd,buf,4096))>0)
{
buf[readed] = 0;
printf("readed:%d\r\n%s",readed,buf);
}
close(fd);
return 0;
}