#include<stdio.h> #include<string.h> #include<stdlib.h> #include<errno.h> #include<unistd.h> #include<sys/types.h> #include<sys/wait.h> #define ERROR_CODE -2 void error_exit(char *err_str,int ret_code); void sort(char*input[],int i); int main(int argc,char *argv[]) { FILE *child_file; FILE *fp; char line[300],*my_pid_str,*my_file_name,buffer[10]; char* lines[100]; int i=0,not_empty,k,t1; pid_t pid,my_pid; /*processid */ int status; /*returnedstatusvar */ size_t t; if((fp=fopen(argv[1],"r"))!=NULL) { while(!feof(fp)) { fgets(line,300,fp); not_empty=0; for(t=0;t<strlen(line);t++) if(line[t]!=' ')not_empty=1; if(not_empty&&line!="\n"&&line!="\t"&&line!="") i++; // lines[i]=strdup(line); } } k=i/100; rewind(fp); printf("number of process to be create is %d\n",k); for(t=1;t<=k;t++) { if((pid=fork())<0) error_exit("Fork error",-1); /*if the fork returns 0- it's a child process*/ else if(pid==0){ i=0; printf("a child is running\n"); while(i<100 && !feof(fp)) { fgets(line,300,fp); not_empty=0; for(t1=0;t1<strlen(line);t1++) if(line[t1]!=' ') not_empty=1; if(not_empty&&line!="\n"&&line!="\t"&&line!="") { lines[i]=strdup(line); i++; } } printf("calling sort\n"); sort(lines,i); printf("return from sort\n"); my_pid=getpid(); printf("proces pid %d\n",my_pid); //strcpy(my_file_name,""); sprintf(my_file_name,"%d.dat",my_pid); printf("file name of the child is %s\n",my_file_name); if((child_file=fopen(my_file_name,"w"))!=NULL) { for(t1=0;t1<i;t1++) fprintf(child_file,"%s\n",lines[t1]); fclose(child_file); } else printf("error open child file"); printf("the child proses is die\n"); exit(0); } if((pid=waitpid(pid,&status,0))<0) error_exit("Error during waitpid",ERROR_CODE); } } void error_exit(char *err_str,int ret_code) { perror(err_str); exit(ret_code); } void sort(char *input[],int i) { int change=1,t; char temp[300]; while(change) { change=0; for(t=0;t<i-2;t++) if (strcmp(input[t],input[t+1])>0) { //printf("%d\n",t); strcpy(temp,input[t]); //printf("temp=%s",temp); input[t]=(char*)malloc(strlen(input[t+1])+1); strcpy(input[t],input[t+1]); //printf("input[t]=%s",input[t]); input[t+1]=(char*)malloc(strlen(temp)+1); strcpy(input[t+1],temp); //printf("input[t+1]=%s\n",input[t]); change=1; } } }
|