Before the tutorial session, try your best to solve problems below and be prepared to discuss them at the tutorial session.
LINE A
.
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
int value = 5;
int main()
{
pid_t pid;
pid = fork();
if (pid == 0) {
/* child process */
value += 15;
return 0;
}
else if (pid > 0) {
/* parent process */
wait(NULL);
printf("PARENT: value = %d",value); /* LINE A */
return 0;
}
}
#include <stdio.h>
#include <unistd.h>
int main()
{
/* fork a child process */
fork();
/* fork another child process */
fork();
/* and fork another */
fork();
return 0;
}
A
, B
, C
, and D
. (Assume that the actual pids of the parent and child are 2600
and 2603
, respectively.)
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
pid_t pid, pid1;
/* fork a child process */
pid = fork();
if (pid < 0) {
/* error occurred */
fprintf(stderr, "Fork Failed\n");
return 1;
}
else if (pid == 0) {
/* child process */
pid1 = getpid();
printf("child: pid = %d\n",pid); /* A */
printf("child: pid1 = %d\n",pid1); /* B */
}
else {
/* parent process */
pid1 = getpid();
printf("parent: pid = %d\n",pid); /* C */
printf("parent: pid1 = %d\n",pid1); /* D */
wait(NULL);
}
return 0;
}
X
and Y
.
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#define SIZE 5
int nums[SIZE] = {0,1,2,3,4};
int main()
{
int i;
pid_t pid;
pid = fork();
if (pid == 0) {
for (i = 0; i < SIZE; i++) {
nums[i] *= -i;
printf("CHILD: %d \n",nums[i]); /* LINE X */
}
}
else if (pid > 0) {
wait(NULL);
for (i = 0; i < SIZE; i++)
printf("PARENT: %d \n",nums[i]); /* LINE Y */
}
return 0;
}
pid_t pid;
pid = fork();
if (pid == 0) { /* child process */
fork();
thread create( . . .);
}
fork();
LINE C
and LINE P
?
#include <pthread.h>
#include <stdio.h>
int value = 0;
void *runner(void *param); /* the thread */
int main(int argc, char *argv[])
{
pid_t pid;
pthread_t tid;
pthread_attr_t attr;
pid = fork();
if (pid == 0) { /* child process */
pthread_attr_init(&attr);
pthread_create(&tid,&attr,runner,NULL);
pthread_join(tid,NULL);
printf("CHILD: value = %d \n",value); /* LINE C */
} else if (pid > 0) { /* parent process */
wait(NULL);
printf("PARENT: value = %d \n",value); /* LINE P */
}
}
void *runner(void *param) {
value = 5;
pthread_exit(0);
}
#include <stdio.h>
#include <inttypes.h>
float power(float x, uint32_t exp);
float power(float x, uint32_t exp)
{
float result;
/* base case */
if (exp == 0)
return 1.0;
result = power(x, exp >> 1);
result = result * result;
if (exp & 1)
result = result * x;
return result;
}
int main(int argc, char **argv)
{
float p;
p = power(10.0, 5);
printf("p = %f\n", p);
return 0;
}
** Version 2 **
#include <stdio.h>
#include <inttypes.h>
float power(float x, uint32_t exp)
{
/* base case */
if (exp == 0) {
return 1.0;
}
/* recursive case */
return x*power(x, exp - 1);
}
int main(int argc, char **argv)
{
float p;
p = power(10.0, 5);
printf("p = %f\n", p);
return 0;
}
Discuss the exercises prepared at home