0

I have to make a shell in C, what should be a simple task is giving me trouble. The following code prints out the text and continually inputs, but only does the printf once.

 printf("(pid=%ld)%s$", (long int)pid,cwd);
 fflush(stdout);
 while((bytes_read=getline(&line,&len,fp))){} 

This code immediately infinite loops doing nothing but printing. I can't get any input.

 do{
     printf("(pid=%ld)%s$", (long int)pid,cwd);
     fflush(stdout);
 }while((bytes_read=getline(&line,&len,fp)));

How can I continually accept input in C like console applications do? I'm not sure why the program is behaving like this.

Dan
  • 176
  • 1
  • 11
  • `getline` returns `-1` if it fails, but you aren't checking for it. So if it fails, the loop continues. And what does `fp` refer to? – lurker Sep 28 '13 at 22:12
  • Were you the guy who just posted a comment? If so the code you posted works. fp is a file pointer that points to dev/null and is required for the function. I honestly have no idea why and I don't particularly care. – Dan Sep 28 '13 at 22:14
  • Yes I did, but I was uncertain about how `fp` was being used, so I wasn't totally happy with my comment as a complete answer. I believe `getline` reads from that file pointer, so you probably just want `stdin`. – lurker Sep 28 '13 at 22:16
  • I think that's correct. – Dan Sep 28 '13 at 22:21

1 Answers1

1

In both cases, if this fails:

bytes_read=getline(&line,&len,fp)

It returns -1 (not 0) which has a truth value of "true". So the while will go on continually. fp isn't defined in the problem statement, so it's unclear what file it is referring to.

Try:

do {
    printf("(pid=%ld)%s$", (long int)pid, cwd);
    fflush(stdout);
} while((bytes_read = getline(&line, &len, stdin)) != -1);

This loop obviously doesn't do anything with the line read, but you can fill that in. :)

I'd probably adjust the logic a little though, to operate on the line within the loop:

do {
    printf("(pid=%ld)%s$", (long int)pid, cwd);
    fflush(stdout);

    if ((bytes_read = getline(&line, &len, stdin)) > 0 ) {
        // Process the line
    }
} while ( bytes_read >= 0 );        
lurker
  • 56,987
  • 9
  • 69
  • 103