fork_demo.c
/***************************************************************/
/* This demo is designed for fork(). */
/* Author:Yuq Date:2023-9-12 */
/***************************************************************/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int i=0;
int main()
{
int pid=fork();
if(pid==-1)
{
printf("fork() failed!");
exit(-1);
} else if(pid==0)
{
i=i+10;
printf("This is child process,i=%d.\n",i);
}
else
{
i=i+20;
printf("This is the parent process,i=%d.\n",i);
wait(NULL);
}
return 0;
}
thread.c
/****************************************************************/
/* This demo is designed for showing multithreads stack address.*/
/* Author:Yuq */
/* Date:2024-3-1 */
/****************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NUM_THREADS 5
void* print_stack_variable_address(void * arg)
{
int stack_variable=42;
pthread_t thread_id=pthread_self();
printf("Thread ID:%lu -stack variable address:%p-value:%d\n",(unsigned long)thread_id,(void *)&stack_variable,stack_variable);
return NULL;
}
int main()
{
pthread_t threads[NUM_THREADS];
for(int i=0;i<NUM_THREADS;i++)
{
if(pthread_create(&threads[i],NULL,print_stack_variable_address,NULL)!=0)
{
perror("pthread_create");
return -1;
}
}
for(int i=0;i<NUM_THREADS;i++)
{
if(pthread_join(threads[i],NULL)!=0)
{
perror("pthread_join");
return -1;
}
}
return 0;
}
pthread.c
/**************************************************************************/
/* This demo is designed for thread creating. */
/* Author:Yuq Date:2023-9-11 */
/**************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void thread()
{
printf("This is a thread.\n");
sleep(10);
}
int main()
{
pthread_t id;
int i,ret;
ret=pthread_create(&id,NULL,(void*)thread,NULL);
if(ret!=0)
{
printf("Creating thread error!\n");
exit(1);
}
printf("This is the main process.\n");
pthread_join(id,NULL);
return 0;
}