0

this is my code

int main(int argc, char **argv)
{

    pid_t child = fork();

    char * argument = argv[1];

    if (child < 0)
    {
        perror("fork");
    } 
    else if (child == 0)
    {
        if (argument == "What")
        {
            write(STDOUT_FILENO, "Yes i did it", 11);
        }
        else
        {
            write(STDOUT_FILENO, "Something went wrong...", 23);
        }
        exit(0);
    }
    else
    {

    }
    return 0;
}

every time i run it with gcc example.c -o name then run it with ./name What but every time on the console is written Something went wrong.... how could i gain access to my first command line argument.

Michael
  • 3,093
  • 7
  • 39
  • 83
Todor Dimitrov
  • 58
  • 2
  • 11
  • 3
    C strings should be compared with `strcmp` – 0xAX Jan 25 '18 at 17:04
  • Read the chapter dealing with strings in your C text book – Jabberwocky Jan 25 '18 at 17:04
  • Not directly related, but `write(STDOUT_FILENO, "Yes i did it", 11);` is very fishy. What would you do if all of a sudden you decide to change the text to `"Wow, perfect, I really did it, isn't it great?"`? – Jabberwocky Jan 25 '18 at 17:06
  • Not only that. Another issue with `write` is that it doesn't guarantee to write all the bytes you ask it to write. Use `printf` instead. – ikegami Jan 25 '18 at 17:08
  • 1
    @ikegami: That's not really an accurate objection ("`write` doesn't guarantee to write all the bytes you ask it to write"). Neither does `printf()`, which on a Unix system usually relies on `write()` to do the dirty work. OTOH, the only times `write()` won't write all the bytes are when there are failures of some sort — no space left on the device, or a socket is closed, or a pipe has no reader left, or … There are reasons to use `printf()` instead of `write()` — that isn't one of them. – Jonathan Leffler Jan 25 '18 at 17:17
  • @Jonathan Leffler, You are wrong. `write` will return prematurely when writing to a full pipe or socket. `printf` will block instead (although I don't know if that's guaranteed). – ikegami Jan 25 '18 at 17:20
  • 1
    @ikegami: write blocks on a full pipe unless you've set `O_NONBLOCK`. It's also covered under the `...` in my comment, and my basic point is still valid. – Jonathan Leffler Jan 25 '18 at 17:22
  • @jonathan: i don't think that is quite correct. If you `write` to a pipe which is not full but does not have capacity for the full write, you can get a partial write with no error (returning the number of bytes written), whether or not the FD is non-blocking. `printf` will restart the underlying `write` automatically. – rici Jan 25 '18 at 17:34
  • @Jonathan Leffler, My comments still apply to sockets even if they don't for pipes. – ikegami Jan 25 '18 at 17:45

1 Answers1

2

You are comparing pointers. The pointer returned by "What" will obviously be different than the pointer to the parameter, so the check will always fail. Use strcmp.

ikegami
  • 367,544
  • 15
  • 269
  • 518