1

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?

  • [fgets manual](https://linux.die.net/man/3/fgets): *If a newline is read, it is stored into the buffer.* That is, the file name in `inpt` has a newline character. Strip that trailing newline character before starting the child process with it. – kaylum Apr 11 '21 at 22:43
  • Have you tried reducing the problem to a [mre]? – EOF Apr 11 '21 at 22:44
  • `freopen(argv[1], "r",stdin);`Tip: Write robust code that is also easier to debug - check all function return values for errors. – kaylum Apr 11 '21 at 22:47

0 Answers0