if (fork() == 0){
execlp("date","date",NULL);
execlp("ls","ls",NULL);
}
I need to enter the date and list the files but it only shows me the first one that would be the date
if (fork() == 0){
execlp("date","date",NULL);
execlp("ls","ls",NULL);
}
I need to enter the date and list the files but it only shows me the first one that would be the date
Each time you call fork()
you are creating a new process. If the result of fork()
is different from 0 is that the current process is the main one and, if not, it is a secondary one.
When the second process is created, all the memory of the main process is copied, so that the processes will not share memory.
The fact is that after fork()
you will have two processes that will execute the same code. You can also identify the current process by calling getpid()
.
Regarding your problem, the fault lies in the fact that the two instructions are within the same if
, then only one of the two processes will execute them ... the other will not do absolutely nothing because you can not enter the if
. Solution? Put an instruction in if
and another in else
:
int pid = fork();
if( pid != 0 )
{
// A ejecutar en el proceso principal
execlp("date","date",NULL);
}
else
{
// A ejecutar en el proceso secundario
execlp("ls","ls",NULL);
}
Keep in mind that if both processes are going to write to the console, their results may intermingle (when executed in parallel) generating strange messages.
Greetings.