FCS351 Prac02 Question 1 #include #include int main() { pid_t pid; pid_t ppid; uid_t uid; int i = 0; int numChilds = 3; pid = getpid(); ppid = pid; while( i < 3 ) { pid = getpid(); if (pid == ppid) { printf("parent\n"); pid = fork(); i++; if ( pid == 0 ) { printf("child\n"); printf("child ID : %d\n",getpid()); printf("parent ID : %d\n",getppid()); printf("user ID : %d\n",getuid()); break; } } else { printf("error\n"); } } return 0; } FCS351 Prac02 Question 2 #include #include // function void *sleeping() { // execute printf() printf("%d says : Hello World!\n",pthread_self()); // sleep for awhile sleep(1); // nothing else for thread to execute pthread_exit(0); } int main() { pthread_t tid[3]; int i; int numThreadsCreated = 0; int numThreadsJoined = 0; // create 3 threads for( i = 0 ; i < 3 ; i++ ) { // create thread and put it in tid array and execute function sleeping // with no parameters passed if(pthread_create(&tid[i], NULL, sleeping, NULL)) { // if created succesfully, record number of threads running numThreadsCreated++; } // fail to create else { printf("thread cannot be created.\n"); } } printf ("%d threads created.\n",numThreadsCreated); // Join all created threads for ( i = 0 ; i < numThreadsCreated ; i++ ) { // joint all threads in the array of index i if(pthread_join(tid[i], NULL)) { // record number of threads joined numThreadsJoined++; } // fail to join else { printf("thread cannot be joined.\n"); } } printf ("%d threads joined.\n",numThreadsJoined); return (0); } FCS351 Prac02 Question 3 #include #include #include // take in an arguement from the commandline int main(int argc, char *argv[]) { int fd; // only accept one arguement from the commandline if (argc == 2) { // try to open the file specified fd = open(argv[1], O_RDWR|O_CREAT); // if fail to open the file, fd is -1 if(fd == -1) { // error msgs perror("Failed to open file."); printf("strerror : %s\n",strerror(errno)); } // file open success else { // print the file descriptor printf("File descriptor is : %d\n",fd); // write to file write(fd, "hahaha" , 6); } // close the file close(fd); } // not enought or too many arguements else { printf("too many or too few arguements passed.\n"); } return(0); }