Использование функций ядра

Все о программировании под *nix
numput
Заглянувший
Сообщения: 6
Зарегистрирован: 25 янв 2010, 00:19

Использование функций ядра

Сообщение numput »

Я хочу использовать функции и макросы ядра (current_thread_info, for_each_process, do_each_process ... ). Сейчас меня интересует работа со структурой task_struct. она находится где-то здесь /usr/src/kernel.../include/linux/sched.h короче в исходниках linux. Я пишу и компилирую на QT(qmake ..., gmake). Как мне подключить эту структуру к моей программе. В структуре есть макросы #ifdef ... и поэтому структура task_struct и другие структуры могут быть разными (размер). И как использовать недокументированные функции. Подскажите с чего начать где копать!

ZvK
Фанатеющий
Сообщения: 140
Зарегистрирован: 30 май 2006, 18:07
Контактная информация:

Re: Использование функций ядра

Сообщение ZvK »

/me тупо поржал
PS: начать с архитектуры ОС, режимов пользователя и ядра

numput
Заглянувший
Сообщения: 6
Зарегистрирован: 25 янв 2010, 00:19

Re: Использование функций ядра

Сообщение numput »

ZvK писал(а):/me тупо поржал
PS: начать с архитектуры ОС, режимов пользователя и ядра
Может ВЫ мне раскажете. Конкретно по теме! Кажись у root 0я привилегия.

ZvK
Фанатеющий
Сообщения: 140
Зарегистрирован: 30 май 2006, 18:07
Контактная информация:

Re: Использование функций ядра

Сообщение ZvK »

Рекомендую нечто большее, чем отрывистые знания с некоего форума. Возьмите лучше книгу.

Аватара пользователя
Llama
Неотъемлемая часть форума
Сообщения: 9749
Зарегистрирован: 06 фев 2002, 11:40
Откуда: Менск

Re: Использование функций ядра

Сообщение Llama »

numput,
во-первых, хочу вас поблагодарить - вы сделали мой день лучше!
во-вторых - опишите, что же вы примерно пытаетесь получить, что и для чего сделать и зачем вам вдруг понадобились заголовки ядра. У вас там драйвера или своя реализация libc ?
Опыт растет прямо пропорционально выведенному из строя оборудованию

numput
Заглянувший
Сообщения: 6
Зарегистрирован: 25 янв 2010, 00:19

Re: Использование функций ядра

Сообщение numput »

Просто хочу написать свой мониторинг операционной системы скорее реализация libc чем драйвер.
Я немного переформирую вопрос. После загрузки операционной системы в памяти есть необходимые мне функции (current_thread_info, for_each_process, do_each_process ... ). Мне нужно описать прототипы этих функция и присвоить им адресс. Как найти адреса этих функций? Затем этим функциям нужно передавать получать структуры, но структуры имеют размер определенный на этапе компиляции ядра, посредством макросов #ifdef ... Как определить установлены те или иные константы для определения структуры task_struct, так как при QT компиляции (или другим компилятором) программы эти константы точно не будут определены?

ZvK
Фанатеющий
Сообщения: 140
Зарегистрирован: 30 май 2006, 18:07
Контактная информация:

Re: Использование функций ядра

Сообщение ZvK »

Да не вопрос, в System.map (часто кладут с ядром в /boot) есть все адреса :))))

d_fdv
Фанатеющий
Сообщения: 152
Зарегистрирован: 04 ноя 2008, 09:14

Re: Использование функций ядра

Сообщение d_fdv »

Но почему QT?!

ZvK
Фанатеющий
Сообщения: 140
Зарегистрирован: 30 май 2006, 18:07
Контактная информация:

Re: Использование функций ядра

Сообщение ZvK »

и вообще, почему QT ещё не включили в ядро????

numput
Заглянувший
Сообщения: 6
Зарегистрирован: 25 янв 2010, 00:19

Re: Использование функций ядра

Сообщение numput »

А что есть что-то помощней QT в плане графики, мощности библиотеки и простоты?
А как определить размер структуры идей нет?

Аватара пользователя
mend0za
Неотъемлемая часть форума
Сообщения: 2332
Зарегистрирован: 30 авг 2002, 12:33
Откуда: Minsk

Re: Использование функций ядра

Сообщение mend0za »

Сначала вы разберитесь почему не получится из QT вызвать функции и макросы ядра (current_thread_info, for_each_process, do_each_process ... ). А потом, если у вас останутся ещё вопросы после изучения материала, можете приходить снова. С новой формулировкой вашей задачи.

numput
Заглянувший
Сообщения: 6
Зарегистрирован: 25 янв 2010, 00:19

Re: Использование функций ядра

Сообщение numput »

Потому что вылетит 5е прерывание.
Вы лучше мне подскажите как определить размер структуры или найти константы определяемые в task_struct?

ZvK
Фанатеющий
Сообщения: 140
Зарегистрирован: 30 май 2006, 18:07
Контактная информация:

Re: Использование функций ядра

Сообщение ZvK »

размер структуры, понятное дело, 42

numput
Заглянувший
Сообщения: 6
Зарегистрирован: 25 янв 2010, 00:19

Re: Использование функций ядра

Сообщение numput »

Код: Выделить всё

struct task_struct {
	volatile long state;	/* -1 unrunnable, 0 runnable, >0 stopped */
	void *stack;
	atomic_t usage;
	unsigned int flags;	/* per process flags, defined below */
	unsigned int ptrace;

	int lock_depth;		/* BKL lock depth */

#ifdef CONFIG_SMP
#ifdef __ARCH_WANT_UNLOCKED_CTXSW
	int oncpu;
#endif
#endif

	int prio, static_prio, normal_prio;
	unsigned int rt_priority;
	const struct sched_class *sched_class;
	struct sched_entity se;
	struct sched_rt_entity rt;

#ifdef CONFIG_PREEMPT_NOTIFIERS
	/* list of struct preempt_notifier: */
	struct hlist_head preempt_notifiers;
#endif

	/*
	 * fpu_counter contains the number of consecutive context switches
	 * that the FPU is used. If this is over a threshold, the lazy fpu
	 * saving becomes unlazy to save the trap. This is an unsigned char
	 * so that after 256 times the counter wraps and the behavior turns
	 * lazy again; this to deal with bursty apps that only use FPU for
	 * a short time
	 */
	unsigned char fpu_counter;
	s8 oomkilladj; /* OOM kill score adjustment (bit shift). */
#ifdef CONFIG_BLK_DEV_IO_TRACE
	unsigned int btrace_seq;
#endif

	unsigned int policy;
	cpumask_t cpus_allowed;

#ifdef CONFIG_PREEMPT_RCU
	int rcu_read_lock_nesting;
	int rcu_flipctr_idx;
#endif /* #ifdef CONFIG_PREEMPT_RCU */

#if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
	struct sched_info sched_info;
#endif

	struct list_head tasks;

	struct mm_struct *mm, *active_mm;

/* task state */
	struct linux_binfmt *binfmt;
	int exit_state;
	int exit_code, exit_signal;
	int pdeath_signal;  /*  The signal sent when the parent dies  */
	/* ??? */
	unsigned int personality;
	unsigned did_exec:1;
	pid_t pid;
	pid_t tgid;

#ifdef CONFIG_CC_STACKPROTECTOR
	/* Canary value for the -fstack-protector gcc feature */
	unsigned long stack_canary;
#endif
	/* 
	 * pointers to (original) parent process, youngest child, younger sibling,
	 * older sibling, respectively.  (p->father can be replaced with 
	 * p->real_parent->pid)
	 */
	struct task_struct *real_parent; /* real parent process */
	struct task_struct *parent; /* recipient of SIGCHLD, wait4() reports */
	/*
	 * children/sibling forms the list of my natural children
	 */
	struct list_head children;	/* list of my children */
	struct list_head sibling;	/* linkage in my parent's children list */
	struct task_struct *group_leader;	/* threadgroup leader */

	/*
	 * ptraced is the list of tasks this task is using ptrace on.
	 * This includes both natural children and PTRACE_ATTACH targets.
	 * p->ptrace_entry is p's link on the p->parent->ptraced list.
	 */
	struct list_head ptraced;
	struct list_head ptrace_entry;

	/* PID/PID hash table linkage. */
	struct pid_link pids[PIDTYPE_MAX];
	struct list_head thread_group;

	struct completion *vfork_done;		/* for vfork() */
	int __user *set_child_tid;		/* CLONE_CHILD_SETTID */
	int __user *clear_child_tid;		/* CLONE_CHILD_CLEARTID */

	cputime_t utime, stime, utimescaled, stimescaled;
	cputime_t gtime;
	cputime_t prev_utime, prev_stime;
	unsigned long nvcsw, nivcsw; /* context switch counts */
	struct timespec start_time; 		/* monotonic time */
	struct timespec real_start_time;	/* boot based time */
/* mm fault and swap info: this can arguably be seen as either mm-specific or thread-specific */
	unsigned long min_flt, maj_flt;

  	cputime_t it_prof_expires, it_virt_expires;
	unsigned long long it_sched_expires;
	struct list_head cpu_timers[3];

/* process credentials */
	uid_t uid,euid,suid,fsuid;
	gid_t gid,egid,sgid,fsgid;
	struct group_info *group_info;
	kernel_cap_t   cap_effective, cap_inheritable, cap_permitted, cap_bset;
	struct user_struct *user;
	unsigned securebits;
#ifdef CONFIG_KEYS
	unsigned char jit_keyring;	/* default keyring to attach requested keys to */
	struct key *request_key_auth;	/* assumed request_key authority */
	struct key *thread_keyring;	/* keyring private to this thread */
#endif
	char comm[TASK_COMM_LEN]; /* executable name excluding path
				     - access with [gs]et_task_comm (which lock
				       it with task_lock())
				     - initialized normally by flush_old_exec */
/* file system info */
	int link_count, total_link_count;
#ifdef CONFIG_SYSVIPC
/* ipc stuff */
	struct sysv_sem sysvsem;
#endif
#ifdef CONFIG_DETECT_SOFTLOCKUP
/* hung task detection */
	unsigned long last_switch_timestamp;
	unsigned long last_switch_count;
#endif
/* CPU-specific state of this task */
	struct thread_struct thread;
/* filesystem information */
	struct fs_struct *fs;
/* open file information */
	struct files_struct *files;
/* namespaces */
	struct nsproxy *nsproxy;
/* signal handlers */
	struct signal_struct *signal;
	struct sighand_struct *sighand;

	sigset_t blocked, real_blocked;
	sigset_t saved_sigmask;	/* restored if set_restore_sigmask() was used */
	struct sigpending pending;

	unsigned long sas_ss_sp;
	size_t sas_ss_size;
	int (*notifier)(void *priv);
	void *notifier_data;
	sigset_t *notifier_mask;
#ifdef CONFIG_SECURITY
	void *security;
#endif
	struct audit_context *audit_context;
#ifdef CONFIG_AUDITSYSCALL
	uid_t loginuid;
	unsigned int sessionid;
#endif
	seccomp_t seccomp;

#ifdef CONFIG_UTRACE
	struct utrace *utrace;
	unsigned long utrace_flags;
#endif

/* Thread group tracking */
   	u32 parent_exec_id;
   	u32 self_exec_id;
/* Protection of (de-)allocation: mm, files, fs, tty, keyrings */
	spinlock_t alloc_lock;

	/* Protection of the PI data structures: */
	spinlock_t pi_lock;

#ifdef CONFIG_RT_MUTEXES
	/* PI waiters blocked on a rt_mutex held by this task */
	struct plist_head pi_waiters;
	/* Deadlock detection and priority inheritance handling */
	struct rt_mutex_waiter *pi_blocked_on;
#endif

#ifdef CONFIG_DEBUG_MUTEXES
	/* mutex deadlock detection */
	struct mutex_waiter *blocked_on;
#endif
#ifdef CONFIG_TRACE_IRQFLAGS
	unsigned int irq_events;
	int hardirqs_enabled;
	unsigned long hardirq_enable_ip;
	unsigned int hardirq_enable_event;
	unsigned long hardirq_disable_ip;
	unsigned int hardirq_disable_event;
	int softirqs_enabled;
	unsigned long softirq_disable_ip;
	unsigned int softirq_disable_event;
	unsigned long softirq_enable_ip;
	unsigned int softirq_enable_event;
	int hardirq_context;
	int softirq_context;
#endif
#ifdef CONFIG_LOCKDEP
# define MAX_LOCK_DEPTH 48UL
	u64 curr_chain_key;
	int lockdep_depth;
	unsigned int lockdep_recursion;
	struct held_lock held_locks[MAX_LOCK_DEPTH];
#endif

/* journalling filesystem info */
	void *journal_info;

/* stacked block device info */
	struct bio *bio_list, **bio_tail;

/* VM state */
	struct reclaim_state *reclaim_state;

	struct backing_dev_info *backing_dev_info;

	struct io_context *io_context;

	unsigned long ptrace_message;
	siginfo_t *last_siginfo; /* For ptrace use.  */
	struct task_io_accounting ioac;
#if defined(CONFIG_TASK_XACCT)
	u64 acct_rss_mem1;	/* accumulated rss usage */
	u64 acct_vm_mem1;	/* accumulated virtual memory usage */
	cputime_t acct_timexpd;	/* stime + utime since last update */
#endif
#ifdef CONFIG_CPUSETS
	nodemask_t mems_allowed;
	int cpuset_mems_generation;
	int cpuset_mem_spread_rotor;
#endif
#ifdef CONFIG_CGROUPS
	/* Control Group info protected by css_set_lock */
	struct css_set *cgroups;
	/* cg_list protected by css_set_lock and tsk->alloc_lock */
	struct list_head cg_list;
#endif
#ifdef CONFIG_FUTEX
	struct robust_list_head __user *robust_list;
#ifdef CONFIG_COMPAT
	struct compat_robust_list_head __user *compat_robust_list;
#endif
	struct list_head pi_state_list;
	struct futex_pi_state *pi_state_cache;
#endif
#ifdef CONFIG_NUMA
	struct mempolicy *mempolicy;
	short il_next;
#endif
	atomic_t fs_excl;	/* holding fs exclusive resources */
	struct rcu_head rcu;

	struct list_head	*scm_work_list;

/*
	 * cache last used pipe for splice
	 */
	struct pipe_inode_info *splice_pipe;
#ifdef	CONFIG_TASK_DELAY_ACCT
	struct task_delay_info *delays;
#endif
#ifdef CONFIG_FAULT_INJECTION
	int make_it_fail;
#endif
	struct prop_local_single dirties;
#ifdef CONFIG_LATENCYTOP
	int latency_record_count;
	struct latency_record latency_record[LT_SAVECOUNT];
#endif
};
Вот структура. 42? Как определял?

ZvK
Фанатеющий
Сообщения: 140
Зарегистрирован: 30 май 2006, 18:07
Контактная информация:

Re: Использование функций ядра

Сообщение ZvK »

ты такой потешный :)

http://en.wikipedia.org/wiki/Phrases_fr ... g_.2842.29

Ответить