You are on page 1of 3

Bi tp

Ch thch cc cu lnh trong nhng on code sau. Thc thi v nu kt qu 1) File System call #include <stdio.h> #include <sys/fcntl.h> #include <errno.h> #define GODEL 10 main(int argc , char argv) { int fdin; int fdout; char *buf[GODEL+1]; int camar; int camaw; memset(buf,0,GODEL+1); fdin = open("dugma1.txt",O_RDONLY); if (fdin < 0) { perror("after open "); exit(-1); } fdout = open("dugma2.txt", O_CREAT | O_RDWR, 0466); if (fdout < 0) { perror("after create "); exit(-1); } do { camar = read(fdin,buf,GODEL); camaw = write(fdout,buf,GODEL); if (camaw < GODEL) { if (errno == EDQUOT) printf(" I need more space \n"); else if (errno == ENOSPC) printf("sys admin: clean the disk \n"); } } while ( (camar == GODEL) && (camaw == GODEL)); lseek(fdout,0,SEEK_SET); write(fdout,"The Start", 10);
1

close(fdin); close(fdout); } 2. C Processes System Calls: Simple example: pid = fork(); if (pid == 0) { /* son */ ret_code = execvp(argv[1],argv); if (ret_code == -1) { perror("exec failed "); exit(-1); } else /* this cannot be reached WHY????*/ ; } else { /* father */ printf("Father: after fork, son proc id is %d \n",pid); waited = wait(&stat); /* stat can tell what happened */ printf("Father: Son proc completed, id is %d \n", waited); } Shell example: while (true) type_prompt(); // display prompt on the screen read_command(command, params); // read input pid = fork(); if (pid < 0) { printf("unable to fork"); //error condition continue; } if (pid > 0) { //parent code wait(&status); // what happends if we dont wait ? } else { //child code execvp(command, params); } }

fork + redirection example: fd = open (moshe.txt , (O_WRONLY | O_CREAT | O_TRUNC) , 0666); pid = fork(); if (pid == 0) { /* son */ printf("Son : %d ;file descriptor: %d \n",getpid(),fd); close(1); /* close stdout*/ dup(fd); /* dup will copy fd into stdout */ close(fd); /* no need for fd anymore*/ ret_code = execvp("hadpes",argv); /*always same exe*/ if (ret_code == -1) { perror("exec failed "); exit(-1); } } else { /* father */ printf("Father: after fork, sons proc id is %d \n", pid); waited = wait(&stat); sprintf (msg, "father caught %d\n" , waited); write(1, msg, strlen(msg)); /* writting to stdout */ } the hadpes.c file: #include <stdio.h> main(){ perror(hadpes start\n); printf(hello world\n); perror(hadpes end\n); }

You might also like