Why is argv[0] not consistent?

From what I understand, argv[0] is the program's path. However, we are doing an assignment and one of my friends gets the name of the first argument when invoking argv[0].

Why does this happen and how can I change this behaviour?

Edit: This is the parent process

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define SIZE 200

int main(int argc, char const *argv[])
{
    char fileName[SIZE];
    int bytesToRead;
    int status;

    bytesToRead = read(0, fileName, SIZE);

    int p[2];
    pipe(p);    
    pid_t pid;

    if((pid = fork()) == -1) {
        perror("error en el fork");
    } else 
    if(pid == 0) { 
        close(p[0]);

        dup2(STDOUT_FILENO, p[1]);
        execl("./printTest", fileName, NULL);

        close(p[1]);
        exit(0);
    } 

    waitpid(pid, &status, 0);

    return 0;
}

And next is a child process:

#include <stdio.h>
#include <unistd.h>

#define SIZE 512

int main(int argc, char const *argv[])
{
    printf("%s\n",argv[0]);
    printf("Exec executed\n");

    return 0;
}

From what we understand, argv[0] should hold the program's name, yet it's printing the first argument (whatever was input from stdin in the parent process)

Upvotes: 1

Views: 159

Answers (2)

0___________
0___________

Reputation: 67476

As per C standard argv[0] should contain the program name.

enter image description here

Upvotes: 0

Demindiro
Demindiro

Reputation: 334

argv[0] isn't necessarily the program's path. It is simply the first argument.

It just so happens that by convention, we use it for the program's name.

For your specific case, you need:

execl("./printTest", "./printTest", fileName, NULL);

Note that this means you always should check if argv[0] is defined before using it.

Upvotes: 3

Related Questions