0

this code to search text in files it work like this
./File [text_to_search] [File1_path] [File2_path] [File3_path] ......
like
./File hello /root/Desktop/file1.txt /root/Desktop/file2.txt /root/Desktop/file3.txt

GetLine is my function

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <sys/types.h>
#include <sys/time.h>

/* COLORS To Print */

#define KRED  "\x1B[31m"
#define RESET "\033[0m"

int main(int argc, char *argv[])
{
    if(argc < 3)
    {
        printf(KRED "You Must Insert Word to Search and 1 file path at least\n" RESET);
        return 0;
    }
    int i = 0;
    for (i = 2; i < argc; i++)
    {

        struct timeval start, end;
        long mtime, secs, usecs;
        gettimeofday(&start, NULL);

        pid_t pid;
        pid = fork();
        if(pid <0)
        {
            printf("error\n");
        }
        else if (pid ==0)
        {
            printf ( "Child : Child’s PID: %d\n", getpid());
            printf ( "Child : Parent’s PID: %d\n", getppid());
            GetLines(argv[i] , argv[1]);
        }
        else
        {
            printf ( "Parent : Parent’s PID: %d\n", getpid());
            printf ( "Parent : Child’s PID: %d\n", pid);
            wait(NULL);
        }

        gettimeofday(&end, NULL);
        secs  = end.tv_sec  - start.tv_sec;
        usecs = end.tv_usec - start.tv_usec;
        mtime = ((secs) * 1000 + usecs/1000.0) + 0.5;
        printf("Elapsed time: " KRED "%ld " RESET "millisecs\n\n", mtime);
    }
    return 0;
}
Ammar Midani
  • 55
  • 1
  • 11
  • @PascalCuoq This is not a duplicate of that. The reason it prints twice is different. – P.P Jan 09 '16 at 20:12
  • @l3x Maybe not, I may have been misled by the absence of observed behavior and expected behavior. The question may also be about “what does `fork()` do?” and that is covered by the accepted answer at the duplicate I picked though. – Pascal Cuoq Jan 09 '16 at 20:14

1 Answers1

1

Because code continue to run on both the processes.. One for the parent and one for yhr child.

ariel t
  • 137
  • 1
  • 8
  • 1
    Your answer is correct. A bit more explanation and solve it (such as calling exit from child) wouldn't hurt. +1 regardless. – P.P Jan 09 '16 at 20:19
  • so how to do my code in child only ?? – Ammar Midani Jan 09 '16 at 20:35
  • @user2816538 In the child process (after `GetLines`) call `exit(0)` which would terminate the child proces and it won't carry executing the rest of the code. – P.P Jan 09 '16 at 20:49