Resumen del código de programación del sistema Linux

1. Concepto del hilo del proceso del programa_número de identificación del proceso

Programa: código fuente, instrucciones.

Proceso: un programa en ejecución

Subprocesos: los subprocesos están subordinados a los procesos. Un proceso puede tener varios subprocesos. Los subprocesos comparten directamente los recursos del proceso.

Tarea: algo específico que hacer

#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>

int main(void)
{
	pid_t pid;

	while(1)
	{
		printf("pid = %d\n", getpid()); //当前进程id号
		printf("ppid = %d\n", getppid());//当前进程父进程id号
		printf("Hello world\n");
		sleep(1);
	}

	return 0;
}

resultado de la operación:

 pstree -p

Puede ver nuestro árbol de procesos, que es la relación del proceso.

 

systemd(init): el proceso padre de todos los procesos

2. Cola de mensajes

#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/msg.h>

#define MY_TYPE  9527

int main(void)
{
	int msgid;
	pid_t pid;

	struct msgbuf
	{
		long mtype;
		char mtext[100];
		int number;
	};

	struct msgbuf buff;

	msgid = msgget(IPC_PRIVATE, 0666 | IPC_EXCL); /* 不晓得为什么必须加上0666才可以*/

	if (msgid == -1) {
	    perror("msgget");
	    return -1;
	}

	pid = fork();

	if(pid > 0)
	{
	    sleep(1);

		buff.mtype = MY_TYPE;
		printf("Please enter a string you want to send:\n");
		gets(buff.mtext);
		printf("Please enter a nubmer you want to send:\n");
		scanf("%d", &buff.number);

		msgsnd(msgid, &buff, sizeof(buff) - sizeof(buff.mtype), 0);

		waitpid(pid, NULL, 0);
	}
	else if(pid == 0)
	{
		printf("Child process is waiting for msg:\n");
		msgrcv(msgid, &buff, sizeof(buff) - sizeof(buff.mtype), MY_TYPE, 0);
		printf("Child process read from msg: %s, %d\n", buff.mtext, buff.number);
	}
	else
		perror("fork");

	return 0;
}

resultado de ejecución:

Utilice colas de mensajes para comunicarse entre diferentes procesos.

recibir código parcial

#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/msg.h>

#define MY_TYPE  9527
#define MY_KEY	 1314

int main(void)
{
	int msgid;

	struct msgbuf
	{
		long mtype;
		char mtext[100];
		int number;
	};

	struct msgbuf buff;

	msgid = msgget(MY_KEY, IPC_CREAT|0644);

	while(1)
	{
		printf("Process is waiting for msg:\n");
		msgrcv(msgid, &buff, sizeof(buff) - sizeof(buff.mtype), MY_TYPE, 0);
		printf("Process read from msg: %s, %d\n", buff.mtext, buff.number);
	}
	msgctl(msgid, IPC_RMID, NULL);

	return 0;
}

Enviar código parcial

#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/msg.h>

#define MY_TYPE  9527
#define MY_KEY	 1314

int main(void)
{
	int msgid;

	struct msgbuf
	{
		long mtype;
		char mtext[100];
		int number;
	};

	struct msgbuf buff;

	msgid = msgget(MY_KEY, IPC_CREAT); //ftok

	buff.mtype = MY_TYPE;
	printf("Please enter a string you want to send:\n");
	gets(buff.mtext);
	printf("Please enter a nubmer you want to send:\n");
	scanf("%d", &buff.number);

	msgsnd(msgid, &buff, sizeof(buff) - sizeof(buff.mtype), 0);

	return 0;
}

 resultado de ejecución

 El problema que encontré fue que al principio no lo ejecuté con permisos de root, lo que causaba un bucle infinito al recibir mensajes, sin embargo, luego descubrí que después de ejecutarlo con permisos de root, podía recibir mensajes normalmente, sin embargo, cuando ejecuté Lo volví a enviar más tarde, descubrí que después de haberlo enviado tres veces, solo entonces recibí el mensaje por cuarta vez. Siguió sucediendo después de intentarlo varias veces. No sé por qué.

Compruébalo con el comando ipcs

--------- 消息队列 -----------
键        msqid      拥有者  权限     已用字节数 消息      
0x00000522 0          root       0          0            0

Es así: no importa cómo recompilo el programa, no funciona, luego reinicio la máquina virtual y descubro que el programa tiene permisos de root. Lo recompilé y funcionó.

Lo volví a verificar con el comando ipcs y descubrí que el propietario y los permisos habían cambiado.

3. Memoria compartida

#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>

char msg[] = "Hello world";

int main(void)
{
	int shmid;
	pid_t pid;

	shmid = shmget(IPC_PRIVATE, 1024, IPC_CREAT);

	pid = fork();

	if(pid > 0)
	{
		char *p_addr;
		p_addr = shmat(shmid, NULL, 0);

		memset(p_addr, '\0', sizeof(msg));
		memcpy(p_addr, msg, sizeof(msg));

		shmdt(p_addr);

		waitpid(pid, NULL, 0);
	}
	else if(pid == 0)
	{
		char *c_addr;
		c_addr = shmat(shmid, NULL, 0);

		printf("Child process waits a short time: \n");
		sleep(3);
		printf("Child Process reads from shared memory: %s\n", c_addr);
		shmdt(c_addr);
	}
	else
		perror("fork");

	return 0;
}

resultado de ejecución:

Un proceso escribe en la memoria compartida y otro proceso lee desde la memoria compartida.

escribir

#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>

char msg[] = "Hello world";

#define MY_KEY	9527

int main(void)
{
	int shmid;

	shmid = shmget(MY_KEY, 1024, IPC_CREAT);

	char *p_addr;
	p_addr = shmat(shmid, NULL, 0);

	memset(p_addr, '\0', sizeof(msg));
	memcpy(p_addr, msg, sizeof(msg));

	shmdt(p_addr);

//	shmctl(shmid, IPC_RMID, NULL);

	return 0;
}

leer

#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>

#define MY_KEY	9527

int main(void)
{
	int shmid;

	shmid = shmget(MY_KEY, 1024, IPC_CREAT);

	char *c_addr;
	c_addr = shmat(shmid, NULL, 0);

	printf("Read from shared memory: %s\n", c_addr);
	shmdt(c_addr);

	return 0;
}

 resultado de ejecución:

destino escribir

Lea de nuevo

4. Bloqueo mutex

utilizado en hilos

pthread_mutex_init inicializa el bloqueo mutex

bloqueo pthread_mutex_lock(&mutex)

cosas para hacer

pthread_mutex_unlock(&mutex) desbloqueo

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

void *thread1_function(void *arg);
void *thread2_function(void *arg);

pthread_mutex_t mutex;

int main(void)
{
	pthread_t pthread1, pthread2;
	int ret;

	pthread_mutex_init(&mutex, NULL);

	ret = pthread_create(&pthread1, NULL, thread1_function, NULL);
	if(ret != 0)
	{
		perror("pthread_create");
		exit(1);
	}

	ret = pthread_create(&pthread2, NULL, thread2_function, NULL);
	if(ret != 0)
	{
		perror("pthread_create");
		exit(1);
	}

	pthread_join(pthread1, NULL);
	pthread_join(pthread2, NULL);
	printf("The thread is over, process is over too.\n");

	return 0;
}

void *thread1_function(void *arg)
{
	int i;

	while(1)
	{
		pthread_mutex_lock(&mutex);
		for(i = 0; i < 10; i++)
		{
			printf("Hello world\n");
			sleep(1);
		}
		pthread_mutex_unlock(&mutex);
		sleep(1);
	}
	return NULL;
}

void *thread2_function(void *arg)
{
	int i;
	sleep(1);

	while(1)
	{
		pthread_mutex_lock(&mutex);
		for(i = 0; i < 10; i++)
		{
			printf("Good moring\n");
			sleep(1);
		}
		pthread_mutex_unlock(&mutex);
		sleep(1);
	}
	return NULL;
}

Efecto de ejecución: primero se bloquea, el hilo se imprime 10 veces primero y luego se desbloquea

Supongo que te gusta

Origin blog.csdn.net/buhuidage/article/details/130181801
Recomendado
Clasificación