- 论坛徽章:
- 5
|
本帖最后由 kaede_1 于 2014-12-23 15:06 编辑
首先,多谢各位回复。有个现象是会有很多次执行正常,应该可以说自己实现的popen在功能上应该是可行的。就是不知道为什么N次之后fork的子进程未执行??
代码如下:- FILE * xs_popen(const char *cmdstring, const char *type)
- {
- int i;
- int pfd[2];
- pid_t pid;
- FILE *fp;
-
- /* only allow "r" or "w" */
- if ((type[0] != 'r' && type[0] != 'w') || type[1] != 0) {
- errno = EINVAL; /* required by POSIX */
- return(NULL);
- }
-
- if (childpid == NULL) { /* first time through */
- /* allocate zeroed out array for child pids */
- maxfd = 1024;
- if ((childpid = calloc(maxfd, sizeof(pid_t))) == NULL)
- {
- return(NULL);
- }
- }
-
- if (pipe(pfd) < 0)
- {
- return(NULL); /* errno set by pipe() */
- }
-
- if ((pid = fork()) < 0) {
- return(NULL); /* errno set by fork() */
- } else if (pid == 0) { /* child */
- if (*type == 'r') {
- close(pfd[0]);
- if (pfd[1] != STDOUT_FILENO) {
- dup2(pfd[1], STDOUT_FILENO);
- close(pfd[1]);
- }
- } else {
- close(pfd[1]);
- if (pfd[0] != STDIN_FILENO) {
- dup2(pfd[0], STDIN_FILENO);
- close(pfd[0]);
- }
- }
- /* close all descriptors in childpid[] */
- for (i = 0; i < maxfd; i++)
- if (childpid[i] > 0)
- close(i);
- execl("/bin/sh", "sh", "-c", cmdstring, (char *)0);
- _exit(127);
- }
-
- /* parent continues... */
- if (*type == 'r') {
- close(pfd[1]);
- if ((fp = fdopen(pfd[0], type)) == NULL)
- return(NULL);
- } else {
- close(pfd[0]);
- if ((fp = fdopen(pfd[1], type)) == NULL)
- return(NULL);
- }
-
- childpid[fileno(fp)] = pid; /* remember child pid for this fd */
- return(fp);
- }
复制代码 |
|