标签:
练习题 8.6:编写一个叫做myecho的程序,它打印出它的命令行参数和环境变量。
#include <unistd.h> #include <sys/types.h> #include <stdlib.h> #include <stdio.h> int main(int argc, char *argv[], char *envp[]) { printf("Command line arguments:\n"); for (int i = 0; i < argc; ++ i) printf(" argv[%d]: %s\n", i, argv[i]); printf("Enviroment variables:\n"); for (int i = 0; envp[i]; ++ i) printf(" envp[%d]: %s\n", i, envp[i]); return 0; }
练习题8.20:使用execve编写一个名为myls的程序,该程序的行为和 /bin/ls 程序一样。
// myls.c #include <unistd.h> #include <sys/types.h> #include <stdlib.h> extern char **environ; int main(int argc, char *argv[]) { execve("/bin/ls", argv, environ); exit(0); }
练习题 8.22
// mysystem.c #include <unistd.h> #include <sys/types.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> extern int erron; extern char **environ; extern int EINTP; int mysystem(char *command) { pid_t pid; int status; if (command == NULL) return -1; if ((pid = fork()) == -1) return -1; if (pid == 0) { char *argv[4]; argv[0] == "sh"; argv[1] == "-c"; argv[2] == command; argv[3] == NULL; execve("bin/sh", argv, environ); exit(-1); // control should never come here } while (1) { if (waitpid(pid, &status, 0) == -1) { if (errno != EINTR) exit(-1); } else { if (WIFEXITED(status)) return WEXITSTATUS(status); else return status; } } }
标签:
原文地址:http://www.cnblogs.com/tallisHe/p/4419512.html