123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172 |
- #include <stdio.h>
- #include <stdlib.h>
- #include <paths.h>
- #include <errno.h>
- #include <unistd.h>
- #include <sys/wait.h>
- #include <bits/uClibc_mutex.h>
- #ifndef VFORK_LOCK
- __UCLIBC_MUTEX_STATIC(mylock, PTHREAD_MUTEX_INITIALIZER);
- # define VFORK_LOCK __UCLIBC_MUTEX_LOCK(mylock)
- # define VFORK_UNLOCK __UCLIBC_MUTEX_UNLOCK(mylock)
- #endif
- struct popen_list_item {
- struct popen_list_item *next;
- FILE *f;
- pid_t pid;
- };
- static struct popen_list_item *popen_list /* = NULL (bss initialized) */;
- FILE *popen(const char *command, const char *modes)
- {
- FILE *fp;
- struct popen_list_item *pi;
- struct popen_list_item *po;
- int pipe_fd[2];
- int parent_fd;
- int child_fd;
- int child_writing;
- pid_t pid;
- child_writing = 0;
- if (modes[0] != 'w') {
- ++child_writing;
- if (modes[0] != 'r') {
- __set_errno(EINVAL);
- goto RET_NULL;
- }
- }
- if (!(pi = malloc(sizeof(struct popen_list_item)))) {
- goto RET_NULL;
- }
- if (pipe(pipe_fd)) {
- goto FREE_PI;
- }
- child_fd = pipe_fd[child_writing];
- parent_fd = pipe_fd[1-child_writing];
- if (!(fp = fdopen(parent_fd, modes))) {
- close(parent_fd);
- close(child_fd);
- goto FREE_PI;
- }
- VFORK_LOCK;
- if ((pid = vfork()) == 0) {
- close(parent_fd);
- if (child_fd != child_writing) {
- dup2(child_fd, child_writing);
- close(child_fd);
- }
-
- for (po = popen_list ; po ; po = po->next) {
- close(po->f->__filedes);
- }
- execl(_PATH_BSHELL, "sh", "-c", command, (char *)0);
-
- _exit(127);
- }
- VFORK_UNLOCK;
-
- close(child_fd);
- if (pid > 0) {
- pi->pid = pid;
- pi->f = fp;
- VFORK_LOCK;
- pi->next = popen_list;
- popen_list = pi;
- VFORK_UNLOCK;
- return fp;
- }
-
- fclose(fp);
- FREE_PI:
- free(pi);
- RET_NULL:
- return NULL;
- }
- int pclose(FILE *stream)
- {
- struct popen_list_item *p;
- int status;
- pid_t pid;
-
- VFORK_LOCK;
- if ((p = popen_list) != NULL) {
- if (p->f == stream) {
- popen_list = p->next;
- } else {
- struct popen_list_item *t;
- do {
- t = p;
- if (!(p = t->next)) {
- __set_errno(EINVAL);
- break;
- }
- if (p->f == stream) {
- t->next = p->next;
- break;
- }
- } while (1);
- }
- }
- VFORK_UNLOCK;
- if (p) {
- pid = p->pid;
- free(p);
- fclose(stream);
-
- do {
- if (waitpid(pid, &status, 0) >= 0) {
- return status;
- }
- if (errno != EINTR) {
- break;
- }
- } while (1);
- }
- return -1;
- }
|