Hello,
I can't figure out how to solve this problem. I know that is not something very difficult, but it doesn't work for me. Any help is important for me, thank you!
For each command line argument, the main process will launch one subprocess.
Each such process will establish if the assigned argument is a director, file or something else.
Based on the established type the subprocess will return to the parent process the followings:
- if the argument is a file then it will return the file size (see st_size from stat).
- if it is a directory then it will return the number of text files (established using file command) found in this directory
or among his subdirectories. To establish the number of text files the process will use popen to execute a shell script. - for cases where the argument is neither a file or a directory it will return a random generated number between 5 and 15.
The communication between the process and his sub processes will be done using a private pipe channel.
Before each read or write pipe operation each process will print what is written or was read from the pipe.
What I did:
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <string.h>
main(int argc, char* argv[]) {
int nr, i, fd[2];
pipe(fd); //make the pipe
struct stat st;
struct stat s;
FILE *f;
FILE *f2;
int status;
char path[50];
//start parsing the arguments
for (i = 1; i < argc; i++) {
//creating a subprocess
if (fork() == 0) {
if(stat(argv,&s)==0)
{ //testing if file
if (s.st_mode & S_IFREG)
{
stat(argv,&st);
nr=st.st_size;
printf("size of file %s is %d\n",argv,nr);
write(fd[1],&nr,sizeof(int));
close(fd[0]);
close(fd[1]);
}
else if(s.st_mode & S_IFDIR) //testing if directory
{
f=popen("find argv -type f | wc -l", "r");
if (f==NULL){
printf("popen error");
}
if (fgets(path,10,f)!=NULL){
fscanf(f,"%d",&nr);
}
status=pclose(f);
if (status==-1){
printf("error closing popen");
}
printf("nr of files in directory %s is %d\n",argv,nr);
write(fd[1],&nr,sizeof(int));
close(fd[0]);
close(fd[1]);
}
}
else
{
//getting a random generated number
nr = rand() % 15 + 5;
printf("a random generated number: %d\n",nr);
write(fd[1],&nr,sizeof(int));
close(fd[0]);
close(fd[1]);
}
// here ends every subprocess
}
//closing the pipe
close(fd[0]);
close(fd[1]);
}
// parent receives what the subprocesses sent
for (i = 1; i < argc; i++) {
read(fd[0],&nr,sizeof(int));
printf("the parent received: %d\n",nr);
close(fd[0]);
close(fd[1]);
}
close(fd[0]);
close(fd[1]);
return 0;
}
When I run it, it prints the message from the parent multiple times and if a directory is passed as argument I get the error: find:argv[i]': No such file or directory`. Also it prints multiple times some of the messages from the subprocesses...