115 lines
2.8 KiB
C
115 lines
2.8 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <unistd.h>
|
|
#include "job.h"
|
|
|
|
job_t *job_list_head = NULL;
|
|
static int next_job_id = 1;
|
|
|
|
// 초기화
|
|
void init_job_list() {
|
|
job_list_head = NULL;
|
|
next_job_id = 1;
|
|
}
|
|
|
|
// 새로운 Job 생성 (껍데기)
|
|
job_t *create_job(char *line) {
|
|
job_t *job = (job_t *)malloc(sizeof(job_t));
|
|
memset(job, 0, sizeof(job_t));
|
|
|
|
job->id = next_job_id++; // ID 자동 할당
|
|
job->command_line = strdup(line); // 원본 보존
|
|
job->state = JOB_RUNNING;
|
|
job->next = NULL;
|
|
job->head = NULL;
|
|
|
|
return job;
|
|
}
|
|
|
|
// 명령어 추가 (파이프라인 연결)
|
|
void append_command(job_t *job, command_t *cmd) {
|
|
if (job->head == NULL) {
|
|
job->head = cmd;
|
|
} else {
|
|
// 리스트 끝을 찾아서 연결
|
|
command_t *curr = job->head;
|
|
while (curr->next != NULL) {
|
|
curr = curr->next;
|
|
}
|
|
curr->next = cmd;
|
|
}
|
|
}
|
|
|
|
// Job 리스트에 등록
|
|
void add_job(job_t *job) {
|
|
if (job_list_head == NULL) {
|
|
job_list_head = job;
|
|
} else {
|
|
job_t *curr = job_list_head;
|
|
while (curr->next != NULL) {
|
|
curr = curr->next;
|
|
}
|
|
curr->next = job;
|
|
}
|
|
}
|
|
|
|
// Job 삭제 (PGID로 찾아서)
|
|
int delete_job(pid_t pgid) {
|
|
job_t *curr = job_list_head;
|
|
job_t *prev = NULL;
|
|
|
|
while (curr != NULL) {
|
|
if (curr->pgid == pgid) {
|
|
// 연결 끊기
|
|
if (prev == NULL) job_list_head = curr->next;
|
|
else prev->next = curr->next;
|
|
|
|
free_job(curr);
|
|
return 1; // 성공
|
|
}
|
|
prev = curr;
|
|
curr = curr->next;
|
|
}
|
|
return 0; // 못 찾음
|
|
}
|
|
|
|
// PGID로 Job 찾기
|
|
job_t *find_job(pid_t pgid) {
|
|
job_t *curr = job_list_head;
|
|
while (curr != NULL) {
|
|
if (curr->pgid == pgid) return curr;
|
|
curr = curr->next;
|
|
}
|
|
return NULL;
|
|
}
|
|
|
|
// ID로 Job 찾기 (fg %1, bg %2 처리용)
|
|
job_t *find_job_by_id(int id) {
|
|
job_t *curr = job_list_head;
|
|
while (curr != NULL) {
|
|
if (curr->id == id) return curr;
|
|
curr = curr->next;
|
|
}
|
|
return NULL;
|
|
}
|
|
|
|
// 메모리 해제 (재귀적으로 Command도 해제)
|
|
void free_command(command_t *cmd) {
|
|
if (cmd == NULL) return;
|
|
free_command(cmd->next); // 재귀 호출로 다음꺼 먼저 삭제
|
|
|
|
// 인자 해제
|
|
// (주의: argv 문자열들이 한 덩어리 buffer를 가리키는지, 각각 malloc인지에 따라 다름)
|
|
// 여기서는 파서 구현에 따라 달라지므로 일단 구조체만 해제
|
|
if (cmd->input_path) free(cmd->input_path);
|
|
if (cmd->output_path) free(cmd->output_path);
|
|
free(cmd);
|
|
}
|
|
|
|
void free_job(job_t *job) {
|
|
if (job == NULL) return;
|
|
free_command(job->head); // 연결된 명령어들 해제
|
|
if (job->command_line) free(job->command_line);
|
|
free(job);
|
|
} |