Thread: Need Urgent helps with print the console

  1. #1
    Registered User
    Join Date
    Oct 2021
    Posts
    5

    Need Urgent helps with print the console

    I just wanted to print out the output of my console but I tried all type of fopen+fprintf() yet the file contain nothing by blank text.
    Code:
    /* Includes */
    #include <unistd.h>     /* Symbolic Constants */
    #include <sys/types.h>  /* Primitive System Data Types */ 
    #include <errno.h>      /* Errors */
    #include <stdio.h>      /* Input/Output */
    #include <stdlib.h>     /* General Utilities */
    #include <pthread.h>    /* POSIX Threads */
    #include <string.h>     /* String handling */
    #include <signal.h>
    #include <sys/mman.h>
    #include <semaphore.h>  /* Semaphore */
    #include <limits.h>
    #include <stdint.h>
    
    /* Global Variables */
    sem_t* semaphore;
    pid_t otherPid;
    sigset_t sigSet;
    pthread_t tid1;
    char file[100];
    FILE* fptr;
    
    void childProcess()
    {
        
        int value;
        //get semaphore value
        sem_getvalue(semaphore, &value);
        printf("Detailed search file count is %d.\n", value);
        fprintf(fptr, "_Detailed search file count is %d._\n", value);
        printf("Detailed search is grabbing the file. \n");
        fprintf(fptr, "_Detailed search is grabbing the file._ \n");
        sem_wait(semaphore);
        sem_getvalue(semaphore, &value);
        printf("Detailed search file count is %d.\n", value);
        fprintf(fptr, "_Detailed search file count is %d._\n", value);
        //START CRITICAL REGION
        printf("Starting to do a detailed search...\n");
        fprintf(fptr,"_Starting to do a detailed search..._\n");
        for(int i =0; i < 60; ++i){
            printf(".\n");
            fprintf(fptr, ".\n");
            sleep(1);
        }
        //END CRITICAL REGION
        sem_post(semaphore);
    
    
        //Exit child process
        printf("Exit detailed search\n");
        fprintf(fptr, "_Exit detailed search_\n");
        _exit(0);
    }
    
    void* checkHungChild(void*a)
    {
        int* status = a;
        //check if child process is waiting long
        printf("Checking if detailed search is doing O.K.....\n");
        fprintf(fptr, "_Checking if detailed search is doing O.K....._\n");
        sleep(10);
        //check if there is a lock on the semaphore
        if(sem_trywait(semaphore) != 0){
            printf("detailed search appears to be taking a while...\n");
            fprintf(fptr, "_detailed search appears to be taking a while..._\n");
            *status = 1;
        }
        else{
            printf("detailed search appears to be running fine...\n");
            fprintf(fptr, "_detailed search appears to be running fine..._\n");
            *status = 0;
        }
        return NULL;
    }
    void parentProcess()
    {
        
        //Detect hung Child Process and kill it after a timeout
        sleep(2);
        //check if child process is running
        if(getpgid(otherPid) >= 0){
            printf("detailed search is running...\n");
            fprintf(fptr,"_detailed search is running..._\n");
        }
        int value;
        sem_getvalue(semaphore, &value);
        printf("The fast search has a total of %d files related to your input.\n", value);
        fprintf(fptr, "_The fast search has a total of %d files related to your input._\n", value);
       //check if there is a lock on the semaphore
        if(sem_trywait(semaphore) != 0){
            pthread_t tid1;
            int status = 0;
            printf("Detecting if detailed search's hung or running to long to find your file....\n");
            fprintf(fptr, "_Detecting if detailed search's hung or running to long to find your file...._\n");
          //check if child process is running a long time
            if(pthread_create(&tid1, NULL, checkHungChild, &status))
            {
                printf("ERROR creating timer thread\n");
                fprintf(fptr,"_ERROR creating timer thread_\n");
                _exit(1);
            }
            if(pthread_join(tid1,NULL)){
                printf("\n ERROR joining timer thread.\n");
                fprintf(fptr,"\n_ERROR joining timer thread._\n");
                _exit(1);
            }
            if(status ==1){
                //Kill child process
                printf("Stopping detailed search on your computer with ID of %d.\n", value);
                fprintf(fptr, "_Stopping detailed search on your computer with ID of %d._\n", value);
                
                kill(otherPid, SIGTERM);
                printf("detailed search ended.\n");
                fprintf(fptr, "_detailed search ended._\n");
    
                //Prove that the child process is killed
                printf("Checking if detailed search has been terminated\n");
                fprintf(fptr,"_Checking if detailed search has been terminated_\n");
                sleep(5);
                kill(otherPid,SIGUSR2);
                sleep(1);
                printf("Confirmed detailed search is done.\n");
                fprintf(fptr,"_Confirmed detailed search is done._\n");
                printf("Started a fast search.\n");
                fprintf(fptr, "_Started a fast search._\n");
                //Try to get semaphore
                sem_getvalue(semaphore, &value);
                printf("Your fast search finds %d file(s).\n", value);
                fprintf(fptr, "_Your fast search finds %d file(s)._\n", value);
                if(sem_trywait(semaphore) != 0)
                {
                    if(value == 0)
                    {
                        sem_post(semaphore);
                        printf("Cleaned up and finally got the file.\n");
                        fprintf(fptr,"_Cleaned up and finally got the file._\n");
                        sem_getvalue(semaphore, &value);
                        printf("The fast search got %d file related to your input.\n", value);
                        fprintf(fptr,"_The fast search got %d file related to your input._\n", value);
    
                    }
                    else{
                        printf("Finally got the file.\n");
                        fprintf(fptr,"_Finally got the file._\n");
                    }
                    //check if the found file is corrupt
                    //if so, delete the file
                    printf("Your file is %s.\n", file);
                    fprintf(fptr,"_Your file is %s._\n", file);
                    if(strcmp(file, "file2") == 0){
                        printf("file is corrupted. Deleting file\n");
                        fprintf(fptr,"_file is corrupted. Deleting file_\n");
                        sem_destroy(semaphore);
                    }
                    
                }
                printf("Exit fast search.\n");
                fprintf(fptr, "_Exit fast search._\n");
                    _exit(0);
            }
        }
    }
    //Utility Methods
    void signalHandeler1(int signum){
        
        printf("Caught Signal: %d\n", signum);
        fprintf(fptr,"_Caught Signal: %d_\n", signum);
        printf(" Exit detailed search Process\n");
        fprintf(fptr,"_Exit detailed search Process_\n");
        sem_post(semaphore);
        _exit(0);
    }
    void signalHandeler2(int signum){
        printf("Singal still alive\n");
        fprintf(fptr,"_Singal still alive_\n");
    }
    
    int main(int argc, char* argv[])
    {
        fptr = fopen("deadlockoutput.txt", "w+");
        
         pid_t pid;
         //ask for user input and make sure input is not empty
         //and its a real file (file1 does not exist)
      do{
        printf("Please input a real file:   ");
        scanf(" %s", file);
        fprintf(fptr,"_Please input a real file:   %s_", file);
      }while(file==NULL || strcmp(file, "file1") == 0 );
        //create shared semaphore
        semaphore = (sem_t*)mmap(0,sizeof(sem_t), PROT_READ|
        PROT_WRITE,MAP_SHARED|
        MAP_ANONYMOUS, -1, 0);
        
        fprintf(fptr, "## Deadlock Program Log File\n\n");
        
        if(sem_init(semaphore,1,1) != 0){
            printf("failed to create semaphore.\n");
            fprintf(fptr, "_failed to create semaphore._\n");
            exit(EXIT_FAILURE);
        }
    
        //use fork()
        setvbuf(stdout, NULL,_IOLBF,0); //so redirect works
        pid = fork();
         if (pid == -1)
        {
            // Error: If fork() returns -1 then an error happened (for example, number of processes reached the limit).
            fprintf(stderr,"Can't fork, error %d\n", errno);
            fprintf(fptr,"_Can't fork, error %d_\n", errno);
            exit(EXIT_FAILURE);
        }
         printf("Searching your computer for file!\n");
         fprintf(fptr,"_Searching your computer for file!_\n");
        // OK: If fork() returns non zero then the parent process is running else child process is running
        if (pid == 0)
        {
            printf("fork() returned 0 to run a fast level search\n");
            fprintf(fptr,"_fork() returned 0 to run a fast level search_\n");
            // Run Producer Process logic as a Child Process
            otherPid = getppid();
            childProcess();
        }
        else
        {
            printf("fork() returned non zero number to run a detailed search\n");
            fprintf(fptr,"_fork() returned non zero number to run a detailed search_\n");
            // Run Consumer Process logic as a Parent Process
            otherPid = pid;
            parentProcess();
        }
        
        fclose(fptr);
        //Cleanup
        sem_destroy(semaphore);
        
        
    
        // Return OK
        return 0;
    }
    Attached Files Attached Files
    Last edited by Salem; 10-13-2021 at 08:39 AM. Reason: Inlined the code

  2. #2
    Registered User
    Join Date
    Dec 2017
    Posts
    1,628
    _exit() doesn't flush open file buffers. exit() does.
    You may wish to flush after every line.
    Instead of writing all output twice you could use a function like this:
    Code:
    void print(const char *fmt, ...) {
        va_list va;
        va_start(va, fmt);
     
        vprintf(fmt, va);
        putchar('\n');
     
        fputc('_', fptr);
        vfprintf(fptr, fmt, va);
        fputc('_', fptr);
        fputc('\n', fptr);
        fflush(fptr);
     
        va_end(va);
    }
     
    // Example of using it (note the removal of \n)
    void childProcess() {
        int value = 0;
        sem_getvalue(semaphore, &value);
     
        print("Detailed search file count is %d.", value);
        print("Detailed search is grabbing the file.");
        sem_wait(semaphore);
        sem_getvalue(semaphore, &value);
        print("Detailed search file count is %d.", value);
     
        //START CRITICAL REGION
        print("Starting to do a detailed search...");
        for (int i = 0; i < 60; ++i) {
            print(".");
            sleep(1);
        }
        //END CRITICAL REGION
        sem_post(semaphore);
     
        //Exit child process
        print("Exit detailed search");
        exit(0);
    }
    A little inaccuracy saves tons of explanation. - H.H. Munro

  3. #3
    Registered User
    Join Date
    Oct 2021
    Posts
    5
    Quote Originally Posted by john.c View Post
    _exit() doesn't flush open file buffers. exit() does.
    You may wish to flush after every line.
    Instead of writing all output twice you could use a function like this:
    Code:
    void print(const char *fmt, ...) {
        va_list va;
        va_start(va, fmt);
     
        vprintf(fmt, va);
        putchar('\n');
     
        fputc('_', fptr);
        vfprintf(fptr, fmt, va);
        fputc('_', fptr);
        fputc('\n', fptr);
        fflush(fptr);
     
        va_end(va);
    }
     
    // Example of using it (note the removal of \n)
    void childProcess() {
        int value = 0;
        sem_getvalue(semaphore, &value);
     
        print("Detailed search file count is %d.", value);
        print("Detailed search is grabbing the file.");
        sem_wait(semaphore);
        sem_getvalue(semaphore, &value);
        print("Detailed search file count is %d.", value);
     
        //START CRITICAL REGION
        print("Starting to do a detailed search...");
        for (int i = 0; i < 60; ++i) {
            print(".");
            sleep(1);
        }
        //END CRITICAL REGION
        sem_post(semaphore);
     
        //Exit child process
        print("Exit detailed search");
        exit(0);
    }
    Thank you so much for your help. I got it fixed.

  4. #4
    Registered User
    Join Date
    Oct 2021
    Posts
    5
    I'm actually open for more suggestion. I had to use fprintf for this assignment and by removing the _ I can only print part of it but not all.

  5. #5
    Registered User
    Join Date
    Oct 2021
    Posts
    5
    Quote Originally Posted by john.c View Post
    _exit() doesn't flush open file buffers. exit() does.
    You may wish to flush after every line.
    Instead of writing all output twice you could use a function like this:
    Code:
    void print(const char *fmt, ...) {
        va_list va;
        va_start(va, fmt);
     
        vprintf(fmt, va);
        putchar('\n');
     
        fputc('_', fptr);
        vfprintf(fptr, fmt, va);
        fputc('_', fptr);
        fputc('\n', fptr);
        fflush(fptr);
     
        va_end(va);
    }
     
    // Example of using it (note the removal of \n)
    void childProcess() {
        int value = 0;
        sem_getvalue(semaphore, &value);
     
        print("Detailed search file count is %d.", value);
        print("Detailed search is grabbing the file.");
        sem_wait(semaphore);
        sem_getvalue(semaphore, &value);
        print("Detailed search file count is %d.", value);
     
        //START CRITICAL REGION
        print("Starting to do a detailed search...");
        for (int i = 0; i < 60; ++i) {
            print(".");
            sleep(1);
        }
        //END CRITICAL REGION
        sem_post(semaphore);
     
        //Exit child process
        print("Exit detailed search");
        exit(0);
    }

    I got coredumped error with semaphore. Please help, thanks.

    Code:
    /* Includes */
    #include <unistd.h>     /* Symbolic Constants */
    #include <sys/types.h>  /* Primitive System Data Types */ 
    #include <errno.h>      /* Errors */
    #include <stdio.h>      /* Input/Output */
    #include <stdlib.h>     /* General Utilities */
    #include <pthread.h>    /* POSIX Threads */
    #include <string.h>     /* String handling */
    #include <signal.h>
    #include <sys/mman.h>
    #include <semaphore.h>  /* Semaphore */
    #include <limits.h>
    #include <stdint.h>
    #include <stdarg.h>
    
    /* Global Variables */
    sem_t* semaphore;
    pid_t otherPid;
    sigset_t sigSet;
    pthread_t tid1;
    char file[100];
    FILE* fptr;
    
    
    
    void print(const char *fmt, ...) {
        va_list va;
        va_start(va, fmt);
      
        vprintf(fmt, va);
        putchar('\n');
      
        fputc('_', fptr);
        vfprintf(fptr, fmt, va);
        fputc('_', fptr);
        fputc('\n', fptr);
        fflush(fptr);
      
        va_end(va);
    }
    
    //Utility Methods
    void signalHandler1(int signum){
        
        //printf("Caught Signal: %d\n", signum);
        print("Caught Signal: %d", signum);
        //printf(" Exit detailed search Process\n");
        print("Exit detailed search Process");
        sem_post(semaphore);
        exit(0);
    }
    void signalHandler2(int signum){
        //printf("Singal still alive\n");
        print("Singal still alive");
    }
    
    
    void childProcess()
    {
         // setup some Signal Handlers
        signal(SIGUSR1, signalHandler1);
        signal(SIGUSR2, signalHandler2);
        
        int value;
        //get semaphore value
        sem_getvalue(semaphore, &value);
        //printf("Detailed search file count is %d.\n", value);
        print("Detailed search file count is %d.", value);
        //printf("Detailed search is grabbing the file. \n");
        print("Detailed search is grabbing the file.");
        sem_wait(semaphore);
        sem_getvalue(semaphore, &value);
        //printf("Detailed search file count is %d.\n", value);
        print("Detailed search file count is %d.", value);
        //START CRITICAL REGION
        //printf("Starting to do a detailed search...\n");
        print("Starting to do a detailed search...");
        for(int i =0; i < 60; ++i){
            //printf(".\n");
            print(".");
            sleep(1);
        }
        //END CRITICAL REGION
        sem_post(semaphore);
    
    
        //Exit child process
        //printf("Exit detailed search\n");
        print("Exit detailed search");
        exit(0);
    }
    
    void* checkHungChild(void*a)
    {
        int* status = a;
        //check if child process is waiting long
        //printf("Checking if detailed search is doing O.K.....\n");
        print("Checking if detailed search is doing O.K.....");
        sleep(10);
        //check if there is a lock on the semaphore
        if(sem_trywait(semaphore) != 0){
            //printf("detailed search appears to be taking a while...\n");
            print("detailed search appears to be taking a while...");
            *status = 1;
        }
        else{
            //printf("detailed search appears to be running fine...\n");
            print("detailed search appears to be running fine...");
            *status = 0;
        }
        return NULL;
    }
    void parentProcess()
    {
        
        //Detect hung Child Process and kill it after a timeout
        sleep(2);
        //check if child process is running
        if(getpgid(otherPid) >= 0){
            //printf("detailed search is running...\n");
            print("detailed search is running...");
        }
        int value;
        sem_getvalue(semaphore, &value);
        //printf("The fast search has a total of %d files related to your input.\n", value);
        print("_The fast search has a total of %d files related to your input.", value);
       //check if there is a lock on the semaphore
        if(sem_trywait(semaphore) != 0){
            pthread_t tid1;
            int status = 0;
            //printf("Detecting if detailed search's hung or running to long to find your file....\n");
            print("Detecting if detailed search's hung or running to long to find your file....");
          //check if child process is running a long time
            if(pthread_create(&tid1, NULL, checkHungChild, &status))
            {
                //printf("ERROR creating timer thread\n");
                print("ERROR creating timer thread");
                _exit(1);
            }
            if(pthread_join(tid1,NULL)){
                //printf("\n ERROR joining timer thread.\n");
                print("\nERROR joining timer thread.");
                _exit(1);
            }
            if(status ==1){
                //Kill child process
                //printf("Stopping detailed search on your computer with ID of %d.\n", value);
                print("Stopping detailed search on your computer with ID of %d.", value);
                
                kill(otherPid, SIGTERM);
                //printf("detailed search ended.\n");
                print("detailed search ended.");
    
                //Prove that the child process is killed
                //printf("Checking if detailed search has been terminated\n");
                print("Checking if detailed search has been terminated");
                sleep(5);
                kill(otherPid,SIGUSR2);
                sleep(1);
                //printf("Confirmed detailed search is done.\n");
                print("Confirmed detailed search is done.");
                //printf("Started a fast search.\n");
                print("Started a fast search.");
                //Try to get semaphore
                sem_getvalue(semaphore, &value);
                //printf("Your fast search finds %d file(s).\n", value);
                print("Your fast search finds %d file(s).", value);
                if(sem_trywait(semaphore) != 0)
                {
                    if(value == 0)
                    {
                        sem_post(semaphore);
                        //printf("Cleaned up and finally got the file.\n");
                        print("Cleaned up and finally got the file.");
                        sem_getvalue(semaphore, &value);
                        //printf("The fast search got %d file related to your input.\n", value);
                        print("The fast search got %d file related to your input.", value);
    
                    }
                    else{
                        //printf("Finally got the file.\n");
                        print("Finally got the file.");
                    }
                    //check if the found file is corrupt
                    //if so, delete the file
                    //printf("Your file is %s.\n", file);
                    print("Your file is %s.", file);
                    if(strcmp(file, "file2") == 0){
                        //printf("file is corrupted. Deleting file\n");
                        print("file is corrupted. Deleting file");
                        sem_destroy(semaphore);
                    }
                    
                }
                //printf("Exit fast search.\n");
                print("_Exit fast search._\n");
                    exit(0);
            }
        }
    }
    
    
    int main(int argc, char* argv[])
    {
        fptr = fopen("deadlockoutput.txt", "w");
        
         pid_t pid;
         //ask for user input and make sure input is not empty
         //and its a real file (file1 does not exist)
      do{
        printf("Please input a real file: ");
        fscanf(stdin, "%s", file);
        
        //print("Please input a real file: %s", file);
        
      }while(file==NULL || strcmp(file, "file1") == 0 );
        
        //create shared semaphore
        semaphore = (sem_t*)mmap(0,sizeof(sem_t), PROT_READ|
        PROT_WRITE,MAP_SHARED|
        MAP_ANONYMOUS, -1, 0);
        
        
        if(sem_init(semaphore,1,1) != 0){
            //printf("failed to create semaphore.\n");
            print("failed to create semaphore.");
            exit(EXIT_FAILURE);
        }
    
        //use fork()
        setvbuf(stdout, NULL,_IOLBF,0); //so redirect works
        pid = fork();
         if (pid == -1)
        {
            // Error: If fork() returns -1 then an error happened (for example, number of processes reached the limit).
            fprintf(stderr,"Can't fork, error %d\n", errno);
            print("Can't fork, error %d", errno);
            exit(EXIT_FAILURE);
        }
         //printf("\nSearching your computer for file!\n");
         print("Searching your computer for file!");
        // OK: If fork() returns non zero then the parent process is running else child process is running
        if (pid == 0)
        {
            //printf("fork() returned 0 to run a fast level search\n");
            print("fork() returned 0 to run a fast level search");
            // Run Producer Process logic as a Child Process
            otherPid = getppid();
            childProcess();
        }
        else
        {
            //printf("fork() returned non zero number to run a detailed search\n");
            print("fork() returned non zero number to run a detailed search");
            // Run Consumer Process logic as a Parent Process
            otherPid = pid;
            parentProcess();
        }
        
        
        //Cleanup
        sem_destroy(semaphore);
        
        fclose(fptr);
        
    
        // Return OK
        return 0;
    }
    Last edited by zhaoyun99; 10-13-2021 at 02:48 PM.

  6. #6
    Registered User
    Join Date
    Dec 2017
    Posts
    1,628
    I forgot to reset the variable arguments for the vfprintf call. It should be:
    Code:
    void print(const char *fmt, ...) {
        va_list va;
        va_start(va, fmt);
     
        vprintf(fmt, va);
        putchar('\n');
     
        va_end(va);
        va_start(va, fmt);
     
        fputc('_', fptr);
        vfprintf(fptr, fmt, va);
        fputc('_', fptr);
        fputc('\n', fptr);
        fflush(fptr);
     
        va_end(va);
    }
    A little inaccuracy saves tons of explanation. - H.H. Munro

  7. #7
    Registered User
    Join Date
    Oct 2021
    Posts
    5
    Thank you so much, I owned you a lot this one.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Somebody please helps me!
    By hchingwong in forum C Programming
    Replies: 3
    Last Post: 09-23-2010, 08:59 PM
  2. Helps with strings
    By 3wit in forum C Programming
    Replies: 3
    Last Post: 05-01-2008, 07:58 AM
  3. Arrays Dev-c++ (please helps)
    By lifeis2evil in forum C++ Programming
    Replies: 19
    Last Post: 12-12-2007, 12:39 PM
  4. Here's a problem, any one helps me?
    By NightWalker in forum C Programming
    Replies: 19
    Last Post: 06-10-2003, 09:19 AM

Tags for this Thread