Home > Blockchain >  Why is this C program doing nothing in Ubuntu?
Why is this C program doing nothing in Ubuntu?

Time:04-21

My very simple C program just hangs and I don’t know why.

I am trying to make a simple executable to handle multiple monotonous actions for me every time I start a new programming session.

So I decided with something simple (below) yet every time I run it, the app just hangs, never returns. So I have to Ctrl-C out of it. I have added printf commands to see if it goes anywhere, but those never appear.

My build command returns no error messages:

gcc -o tail tail.c

Just curious what I am missing.

#include <stdio.h>
#include <unistd.h>
int main() {

    chdir("\\var\\www");
    return 0;
}

CodePudding user response:

There are at least two problems with the source code:

  1. It is unlikely that you have a sub-directory called \var\www in your current directory — Ubuntu uses / and not \ for path separators.

  2. Even if there was a sub-directory with the right name, your program would change directory to it but that wouldn't affect the calling program.

You should check the return value from chdir() — at minimum:

if (chdir("/var/www") != 0)
{
    perror("chdir");
    exit(EXIT_FAILURE);
}

And, as Max pointed out, calling your program by the name of a well-known utility such as tail is likely to lead to confusion. Use a different name.

Incidentally, don't use test as a program name either. That, too, will lead to confusion as it is a shell built-in as well as an executable in either /bin or /usr/bin. There is also a program /bin/cd or /usr/bin/cd on your machine — it will check that it can change directory, but won't affect the current directory of your shell. You have to invoke it explicitly by the full pathname to get it to run at all because cd is another shell built-in.

CodePudding user response:

Two things:

  • First, that's not what Linux paths look like

  • Second, check the return value from chdir()

ie

 if (chdir("/var/www") != 0)
     printf("failed to change directory");

Finally, the effect of chdir() lasts for the duration of the program. It will not change the current directory of your shell once this program finishes.

  • Related