Problem with getting integer value from atoi()

142 Views Asked by At

I am trying to write a simple program which passes the PID of the parent process to the child process and print, however when I use the atoi() function I am not receiving the correct parent PID value. I'm not sure what I am doing wrong. I have read that the atoi() function is ASCII to integer, which makes me wonder if this is the right function. I have read that the command line arguments must be passed as strings. I have just begun learning C, so apologies if this seems like a silly question. I have provide both .c files below.

This is the Parent Process

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

#define COUNT 1

int pfd[2];

int main()
{
    pid_t process_id;

    char pipeReadstr[11];
    char str1_pid[10];

    // Set up the pipe
    pipe(pfd)
    
    sprintf(str1_pid, "%d", getpid());

    //Set up the read file descriptor
    sprintf (pipeReadstr, "%d", pfd[0]);

    process_id = fork();

    if (process_id == 0)
    {
        close(pfd[1]);//Close the write end of pipe 0
        execl("../receiveVar/receiveVar.exe", "receiveVar", pipeReadstr, 
              (char *)NULL);
    }
    sleep(2);

    // Passing str1 to the write end of pipe 0, then close write and read ends
    write(pfd[1], str1_pid, strlen(str1_pid));
    close(pfd[1]);
    close(pfd[0]);
}

This is the Child Process

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define READ_BLOCK_SIZE 10

int main(int argc, char *argv[])
{
    pid_t str = getpid();

    char readBuffer[READ_BLOCK_SIZE+1];
    ssize_t bytesRead;

    int readFd;

    readFd = atoi(argv[1]);
    bytesRead = read(readFd, readBuffer, READ_BLOCK_SIZE);

    while (bytesRead > 0)
    {
        readBuffer[bytesRead] = '\0';
        printf("Child Process: Received parent process PID: %d. Child process read %li bytes.\n", readFd, bytesRead);
        printf("Child Process PID: %d\n", str);
        bytesRead = read(readFd, readBuffer, READ_BLOCK_SIZE);
    }
    close(readFd);
}
1

There are 1 best solutions below

0
Dan On

I have managed to see where I had my error and now the code works fine. I passed the incorrect variable which also meant I had the wrong specifier.

while (bytesRead > 0)
{
    readBuffer[bytesRead] = '\0';
    printf("Child Process: Received parent process PID: %s. Child process read 
    %li bytes.\n", readBuffer, bytesRead);
    printf("Child Process PID: %d\n", str);
    bytesRead = read(readFd, readBuffer, READ_BLOCK_SIZE);
}
close(readFd);