unix环境高级编程,尤晋元,2000年
只是把书里的代码敲一遍跑一下,熟悉一下书里的东西,没什么特别的;
#include <stdio.h> #include <stdlib.h> #include <unistd.h> // list directory content int ls(int, char**); // copy input to output int IO_Nobuffer(); int standardio(); int shell(int, char**); int main(int argc, char** argv) { printf("current process id: %d, user id: %d, group id: %d\n", getpid(), getuid(), getgid()); shell(argc, argv); //standardio(); //IO_Nobuffer(); //ls(argc, argv); exit(0); } #include <sys/types.h> #include <dirent.h> int ls(int argc, char** argv) { if(argc < 2) { printf("a single argument is required!\n"); exit(-1); } DIR* dp; struct dirent* dirp; dp = opendir(argv[1]); if(!dp) { printf("open %s failed!\n", argv[1]); exit(-1); } while((dirp = readdir(dp)) != NULL) { printf("%s\n", dirp->d_name); } closedir(dp); return 0; } #include <unistd.h> #define BUFFER_SIZE 8192 int IO_Nobuffer() { int n; char buffer[BUFFER_SIZE]; while((n = read(STDIN_FILENO, buffer, BUFFER_SIZE)) > 0) { if(write(STDOUT_FILENO, buffer, n) != n) { printf("write error!\n"); exit(-1); } } if(n < 0) { printf("read error!\n"); exit(-1); } return 0; } int standardio() { int c; while((c = getc(stdin))!= EOF) { printf("%d\n", c); if(putc(c, stdout) == EOF) { printf("output error!\n"); exit(-1); } } if(ferror(stdin)) { printf("input error!\n"); exit(-1); } exit(0); } #include <sys/wait.h> #include <string.h> int shell(int argc, char** argv) { char buffer[BUFFER_SIZE]; pid_t pid; int status; printf("%% "); while(fgets(buffer, BUFFER_SIZE, stdin) != NULL) { buffer[strlen(buffer) - 1] = 0; if((pid = fork()) < 0) { printf("fork error!\n"); exit(-1); } else if(pid == 0) // child process { execlp(buffer, buffer, (char*)0); exit(127); } if((pid = waitpid(pid, &status, 0)) < 0) { printf("wait error!\n"); exit(-1); } printf("%% "); } return 0; }
reference
unix环境高级编程<尤晋元>
http://en.wikipedia.org/wiki/Fork_(system_call)
http://unixhelp.ed.ac.uk/CGI/man-cgi?execve+2
http://unixhelp.ed.ac.uk/CGI/man-cgi?execlp+3
http://www.cplusplus.com/reference/cstdio/fgets/
时间: 2024-10-11 13:36:58