- 论坛徽章:
- 0
|
急:LINUX下C小问题
调用系统的system() ,其运行的结果,是显示在标准输出上的,而不是通过返回可以得到的。。
以下的程序是我改过别人的一个my_system(),他可以将运行结果返回到第二个参数中,第一个参数同system()一样接收你要执行的语句,第三个参数表示结果的大小数。
- #include <stdio.h>;
- #include <unistd.h>;
- #include <sys/types.h>;
- #include <stdlib.h>;
- int my_system(const char* pCmd, char* pResult, int size)
- {
- int fd[2];
- int pid;
- int count;
- int left;
- char *p = 0;
- int maxlen =size-1;
- memset(pResult, 0, size);
- /*pipe creates a pair of file descriptors, pointing to a pipe
- inode,and places them in the array pointed to by filedes.
- filedes[0] is for reading, filedes[1] is for writing.
- */
- if(pipe(fd))
- {
- printf("pipe error\n");
- return -1;
- }
-
- if((pid = fork()) == 0)
- {
- // chile process
- int fd2[2];
- if(pipe(fd2))
- {
- printf("pipe2 error\n");
- return -1;
- }
-
- close(1);
- dup2(fd2[1],1);
-
- close(fd[0]);
- close(fd2[1]);
-
- system(pCmd);
- read(fd2[0], pResult, maxlen);
-
- pResult[strlen(pResult)-1] = 0;
-
- write(fd[1], pResult, strlen(pResult));
-
- close(fd2[0]);
- exit(0);
- }
-
- // parent process
- close(fd[1]);
-
- p = pResult;
- left = maxlen;
-
- while((count = read(fd[0], p, left)))
- {
- p+= count;
- left -= count;
- if(left == 0)
- break;
- }
-
- close(fd[0]);
- return 0;
- }
- int main(int argc,char * argv[])
- {
- char *pCommand =argv[1];
- int bufnum = atoi(argv[2]);
- char *result = malloc(1024);
-
- if(argc != 3)
- {
- printf("argument error!\n");
- return;
- }
- my_system(pCommand, result,bufnum);
- printf("the result is\n\n%s\n", result);
- free(result);
- return 0;
- }
复制代码 |
|