使用longjmp,带超时限制调用read

//Set max timeout when block reading
// by Jay Zhang

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <setjmp.h>

static void sig_alarm(int);
static jmp_buf env_alarm;

#define MAXLINE	1024

int main(void)
{
	int n;
	char line[MAXLINE];

	if(signal(SIGALRM, sig_alarm) == SIG_ERR) {
		printf("signal SIGALARM error\n");
		return -1;
	}
	if(setjmp(env_alarm) != 0) {
		printf("read timeout\n");
		return 0;
	}

	alarm(10);
	if((n = read(STDIN_FILENO, line, MAXLINE)) < 0) {
		printf("read error\n");
	}
	alarm(0);

	write(STDOUT_FILENO, line, n);
	return 0;
}

static void
sig_alarm(int signo)
{
	longjmp(env_alarm, 1);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
longjmp是一个C语言库函数,它的作用是跳转到由控制传递给setjmp()函数的位置,并且有一个值作为返回值。在MIPS汇编中,longjmp函数的实现需遵循以下步骤: 1. 保存寄存器和上下文环境。在调用longjmp之前,需要将所有需要保存的寄存器和上下文环境保存在堆栈中,以便程序返回时可以恢复这些值。 2. 设置返回值。根据longjmp的要求,在执行跳转之前,需要将要返回的值存储在合适的寄存器(如v0)中。 3. 跳转回setjmp()设置的位置。在MIPS汇编中,可以使用jr指令跳转到要返回的地址,并将地址保存在寄存器ra中。 下面是一个示例longjmp函数的MIPS汇编代码: ```assembly # longjmp function implementation in MIPS assembly .globl longjmp longjmp: # save the context addi $sp, $sp, -16 sw $a0, 0($sp) # save the jmp_buf pointer sw $s0, 4($sp) # save the saved register s0 sw $s1, 8($sp) # save the saved register s1 sw $ra, 12($sp) # save the return address # set the return value lw $v0, 4($a0) # load the value to return from jmp_buf+4 # jump back to the setjmp() point lw $ra, 0($a0) # load the return address from jmp_buf lw $s1, 8($sp) # restore the saved register s1 lw $s0, 4($sp) # restore the saved register s0 lw $a0, 0($sp) # restore the jmp_buf pointer addi $sp, $sp, 16 # pop the saved context jr $ra # jump back to the setjmp() point ``` 上述代码中,我们首先将上下文环境保存到堆栈中(第2-5行)。然后,我们将要返回的值从jmp_buf+4处加载到寄存器v0中(第8行)。最后,我们恢复保存的寄存器和上下文环境,并使用jr指令直接跳转到返回地址(第13-17行)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值