Pedro Quintans
Pedro Quintans

Reputation: 11

Use of fork() to create folders

I'm currently studying the fork function in Linux and was asked to do a seemingly simple program. The program must create in the current directory, 3 directories ./D1/D2/D3, then change its current directory to D3 and finaly print the absolute path, i'm having trouble right at the beginning.

"The program dir123(process A) must start by creating a local structure directory, creating a new process(Process B) that substitutes its image for mkdir command image and, using option "-p" creats all the tree directories at once"

Can someone please enlighten me about what i need to do? It seems process A is to create the directories like: system("mkdir ./D1/D2/D3");

What i don't know is that i have to use a child process for creating each one of the 3 directories, or using one child to creat all three at once.

It's in portuguese:

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

int main()
{
   pid_t pid, pidw;
   int status;

   printf("\nExemplo de aplicacao 05 da funcao fork()\n");
   pid= fork();
   if ( pid==-1 ) {
      perror("Erro na funcao fork()");
      exit(1);
   }

   if ( pid ) {
      /* pid>0, codigo para o processo pai */
      printf("Codigo do Pai  :  PID=%5d  PPID=%5d\n", \
         (int) getpid(), (int) getppid());
      printf("Codigo do Pai  :  Iniciado wait()\n");
      pidw= wait(&status);
      printf("Codigo do Pai  :  Processo filho PID=%5d" \
         " terminou!\n", (int) pidw);
   }
   else {
      /* pid=0, codigo para o processo filho */
      printf("Codigo do Filho:  PID=%5d  PPID=%5d\n", \
         (int) getpid(), (int) getppid());
    //DIRECTORY CREATION
        system("mkdir -p D1/D2/D3");
      printf("Codigo do Filho:  PID=%5d  PPID=%5d\n", \
         (int) getpid(), (int) getppid());
   }

   return 0;
}

Upvotes: 0

Views: 447

Answers (1)

Joshua
Joshua

Reputation: 43327

"What i don't know is that i have to use a child process for creating each one of the 3 directories, or using one child to creat all three at once."

It's pretty obvious from the problem statement that you're supposed to use the exec*() family of functions to create the directories at once by mkdir -p. You have the right command in your system() call.

Since this is homework I'm not going to give you the answer. The call you want is declared as int execvp(const char *file, char *const argv[]);

A thing new programmers struggle with is the first argument is a duplicate of the program name, so it's going to look more like execvp(args[0], args) where args is an array of char *.

Upvotes: 1

Related Questions