LAB

0 Hello World 

What can C print in the below code? Assume the child’s PID is 90210 (Hint: There is more than one correct answer) 


int main() {

    pid_t pid = fork();

    printf("Hello World: %d\n", pid);

} 


1 Forks 

How many new processes are created in the below program assuming calls to fork succeeds? 


int main(void)

{

  for (int i = 0; i < 3; i++) {

      pid_t pid = fork();

  } 

} 


2 Stack Allocation 

What can C print? 


int main(void)

{

    int stuff = 7;

    pid_t pid = fork();

    printf("Stuff is %d\n", stuff);

    if (pid == 0)

        stuff = 6; 

} 



3 Heap Allocation 

What can C print? 

int main(void)

{

    int* stuff = malloc(sizeof(int)*1);

    *stuff = 7;

    pid_t pid = fork();

    printf("Stuff is %d\n", *stuff);

    if (pid == 0)

        *stuff = 6

} 


4 Slightly More Complex Heap Allocation 

What does C print in this case ? 


void printTenNumbers(int *arr)

{

    int i;

    printf("\n");

    for(i=0; i<10; i++) {

        printf("%d",arr[i]);

    }

    exit(0); 

} 


int main() { 

    int *arr, i;

    arr = (int *) malloc (sizeof(int));


    arr[0] = 0;

    for(i=1; i<10; i++) {

        arr = (int *) realloc( arr, (i+1) * sizeof(int));

        arr[i] = i;

        if (i == 7) {

             pid_t pid = fork();

             if (pid == 0) {

                  printTenNumbers(arr);

             }

       }

   }

   printTenNumbers(arr);

}


5 Simple Wait 

What can C print? Assume the child PID is 90210. 

int main(void)

{

    pid_t pid = fork();

    int exit;

    if (pid != 0) {

        wait(&exit);

    }

    printf("Hello World\n: %d\n", pid);

}


What is the equivalent program using the waitpid function instead of wait? 



6 Fork and File Descriptors 

What will be stored in the file ”output.txt” ? 

int main(void)

{

    int fd; 

    fd = open("output.txt", O_CREAT|O_TRUNC|O_WRONLY, 0666);


    if(!fork()) {

        write(fd, "hello ", 6);

        exit(0);

    } else {

        int status;


        wait(&status);

        write(fd, "world\n", 6);

    }

} 


7 Exec 

What will C print? 

int main(void)

{

    char** argv = (char**) malloc(3*sizeof(char*));

    argv[0] = "/bin/ls";

    argv[1] = ".";

    argv[2] = NULL;

    for (int i = 0; i < 10; i++) {

        printf("%d\n", i);

        if (i == 3)

             execv("/bin/ls", argv);

   } 

} 


8 Exec + Fork 

How would I modify the above program using fork so it both prints the output of ls and all the numbers from 0 to 9 (order does not matter)? You may not remove lines from the original program; only add statements (and use fork!). 

하위 페이지 (1): OLD Lab
Comments