I have two small programs. Here is their code
compiled as c.out
:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(){
int num=255;
char*inpt=malloc(sizeof(char)*num);
fgets (inpt, num, stdin);
pid_t pid;
pid=fork();
if(pid==0){
char*args[]={"./b.out",inpt,NULL};
execvp(args[0],args);
_exit (EXIT_FAILURE);
}
else if(pid<0){
}
else{
}
return 0;
}
and this, compiled as b.out
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int w(int sb){
printf("entered w\n");
for(int i=2;i*i<sb;i++){
if((sb%i)==0){
printf("%d\n",sb);
return 0;
}
}
printf("%d\n",-1);
return 1;
}
int main( int argc, char *argv[] ){
for(int i=0;i<argc;i++){
printf("%s\n",argv[i]);
}
freopen(argv[1], "r",stdin);
int subj;
printf("test c\n");
while (scanf("%d", &subj) == 1){
printf("test d\n");
if(w(subj)){
break;
}
}
return 0;
}
Here is what happens in UNIX shell whe I type echo "input.txt" | ./c.out
:
./b.out
input.txt
test c
and this is the output i get when i type ./b.out input.txt
./b.out
input.txt
test c
test d
entered w
12
test d
entered w
15
test d
entered w
321
test d
entered w
-1
Since im completely new to the topic of parent/child processes, I assumed that calling b.out using c.out would give the same result as just calling b.out. Obviously, this isn't the case. So my question is: why, when called from c.out, b.out does not enter the while() loop? (or if it enters, why can i not see it?)
unrelated question: is there a way to not get blocked after asking just one question?