Search code examples
cheaderforkexecvpinclude-guards

Why is my file executing this header twice even with guards in place while forking in C?


Even with guards in place, my file is still trying to execute the mkdir twice.

I tried putting the ifndef in the other c file but it still executes twice

p.h

#ifndef P_H
#define P_H

void p1(char* filepath, int m);


#endif

main.c

#include "main.h"// includes ifndef with p1.h inside it

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

    p1("Hi",2);

    return 0;

}

p1.c

#include "phase1.h"
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>

void p1(char* filepath, int m){
    pid_t cpid;
    cpid = fork();
    if ((cpid = fork()) == -1) {
        perror("fork failed");
    }
    if(cpid > 0){
        wait(NULL);
    }
    else{
        char *makeDir[] = {"mkdir", "MyNewDirectory", NULL};
        execvp(makeDir[0],makeDir);
    }
}

when I execute gcc -o p1test main.c p1.c and ./p1test, I get the error that mkdir: cannot create directory ‘MyNewDirectory’: File exists". Obviously it is working to make the directory, but then trying to make it again. Aren't the guards supposed to protect against these multiple executions? Does this have something to do with the fork? This is the first time attempting to use custom header files. Thanks in advance and if this is already answered somewhere please let me know and I will delete this.


Solution

  • You are calling fork() twice so you have 4 different processes running. The two children are both trying to create the directory. You only need to call fork() once:

    cpid = fork();
    if (cpid == -1) {
        perror("fork failed");
    }
    

    The header guards are correct and have nothing to do with your issue. They are only used at compile time to make sure that your header file is only included once.