A process can take advantage of the entire C library for dealing with I/O. In addition to the I/O interface provided by the C library, a process may also use POSIX I/O services such as open(), read(), or write(), as well as POSIX socket services such as socket(), bind(), and connect().
The following program can be run as a process and illustrates the way in which the C library can be used from a process.
#include <stdio.h> #include <stdlib.h> #include <chorus.h> #define BUF_SIZE 80 struct stat st; int main(int argc, char** argv, char** envp) { FILE* file; FILE* filew; char* buf; int res; if (argc != 2 && argc != 3) { fprintf(stderr, "Usage: %s filename\n", argv[0]); exit(1); } file = fopen(argv[1], "r"); if (file == NULL) { fprintf(stderr, "Cannot open file %s\n", argv[1]); exit(1); } res = stat(argv[1], &st); if (res < 0) { fprintf(stderr, "Cannot stat file\n"); exit(1); } printf("File size is %d mode 0x%x\n", st.st_size, st.st_mode); buf = (char*) malloc(BUF_SIZE); if (buf == NULL) { fprintf(stderr, "Cannot allocate buffer\n"); exit(1); } bzero(buf, BUF_SIZE); res = read(fileno(file), buf, 80); if (res == -1) { fprintf(stderr, "Cannot read file\n"); exit(1); } printf("%s\n", buf); if (argv[2] != NULL) { filew = fopen(argv[2], "w"); if (filew == NULL) { fprintf(stderr, "Cannot open file %s\n", argv[2]); exit(1); } printf("Type any input you like: \n"); do { scanf("%80s", buf); printf("buf=%s\n", buf); fprintf(filew, "%s", buf); printf("buf=%s\n", buf); } while (buf[0] != 'Q'); } exit(0); }
Referencing argv[0] without checking if argc is greater than zero can cause the process to incur an exception and be deleted.