POSIX(可移植操作系统接口)提供了一组标准的API,供开发人员在类Unix系统上进行编程。以下是一些常见的POSIX编程代码示例:
1. 线程创建和管理
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
void* thread_function(void* arg) {
printf("Hello from thread!\n");
return NULL;
}
int main() {
pthread_t thread;
// 创建线程
if (pthread_create(&thread, NULL, thread_function, NULL) != 0) {
perror("Failed to create thread");
exit(EXIT_FAILURE);
}
// 等待线程结束
pthread_join(thread, NULL);
printf("Thread finished\n");
return 0;
}
2. 文件操作
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
int main() {
int fd = open("example.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
if (fd == -1) {
perror("Error opening file");
return EXIT_FAILURE;
}
const char *text = "Hello POSIX!";
write(fd, text, sizeof(text));
lseek(fd, 0, SEEK_SET); // 回到文件开头
char buffer[100];
read(fd, buffer, sizeof(buffer));
printf("Read from file: %s\n", buffer);
close(fd);
return 0;
}
3. 信号处理
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void signal_handler(int signum) {
printf("Received signal %d\n", signum);
}
int main() {
// 注册信号处理函数
signal(SIGINT, signal_handler);
while (1) {
printf("Running... Press Ctrl+C to stop.\n");
sleep(1);
}
return 0;
}
4. 使用共享内存
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <string.h>
int main() {
int shmid;
const char *message = "Hello Shared Memory";
char *shared_memory;
// 创建共享内存段
shmid = shmget(IPC_PRIVATE, 1024, IPC_CREAT | 0666);
shared_memory = (char *)shmat(shmid, NULL, 0);
strcpy(shared_memory, message);
printf("Shared Memory contains: %s\n", shared_memory);
shmdt(shared_memory); // 分离共享内存
shmctl(shmid, IPC_RMID, NULL); // 删除共享内存
return 0;
}
这些例子展示了使用POSIX API进行多线程、文件操作、信号处理和共享内存管理等基本功能的方式。在实际应用中,可以根据具体需求进行扩展和修改。
内容由零声教学AI助手提供,问题来源于学员提问