Merge changes from emacs-23 branch.
[bpt/emacs.git] / src / process.c
1 /* Asynchronous subprocess control for GNU Emacs.
2 Copyright (C) 1985, 1986, 1987, 1988, 1993, 1994, 1995,
3 1996, 1998, 1999, 2001, 2002, 2003, 2004,
4 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
5
6 This file is part of GNU Emacs.
7
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
12
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20
21
22 #include <config.h>
23 #include <signal.h>
24 #include <stdio.h>
25 #include <errno.h>
26 #include <setjmp.h>
27 #include <sys/types.h> /* some typedefs are used in sys/file.h */
28 #include <sys/file.h>
29 #include <sys/stat.h>
30 #include <setjmp.h>
31 #ifdef HAVE_INTTYPES_H
32 #include <inttypes.h>
33 #endif
34 #include <stdlib.h>
35
36 #ifdef HAVE_UNISTD_H
37 #include <unistd.h>
38 #endif
39 #include <fcntl.h>
40
41 /* Only MS-DOS does not define `subprocesses'. */
42 #ifdef subprocesses
43
44 #include <sys/socket.h>
45 #include <netdb.h>
46 #include <netinet/in.h>
47 #include <arpa/inet.h>
48
49 /* Are local (unix) sockets supported? */
50 #if defined (HAVE_SYS_UN_H)
51 #if !defined (AF_LOCAL) && defined (AF_UNIX)
52 #define AF_LOCAL AF_UNIX
53 #endif
54 #ifdef AF_LOCAL
55 #define HAVE_LOCAL_SOCKETS
56 #include <sys/un.h>
57 #endif
58 #endif
59
60 #if defined(HAVE_SYS_IOCTL_H)
61 #include <sys/ioctl.h>
62 #if defined(HAVE_NET_IF_H)
63 #include <net/if.h>
64 #endif /* HAVE_NET_IF_H */
65 #endif /* HAVE_SYS_IOCTL_H */
66
67 #ifdef NEED_BSDTTY
68 #include <bsdtty.h>
69 #endif
70
71 #ifdef HAVE_SYS_WAIT
72 #include <sys/wait.h>
73 #endif
74
75 #ifdef HAVE_RES_INIT
76 #include <netinet/in.h>
77 #include <arpa/nameser.h>
78 #include <resolv.h>
79 #endif
80
81 #ifdef HAVE_UTIL_H
82 #include <util.h>
83 #endif
84
85 #endif /* subprocesses */
86
87 #include "lisp.h"
88 #include "systime.h"
89 #include "systty.h"
90
91 #include "window.h"
92 #include "buffer.h"
93 #include "character.h"
94 #include "coding.h"
95 #include "process.h"
96 #include "frame.h"
97 #include "termhooks.h"
98 #include "termopts.h"
99 #include "commands.h"
100 #include "keyboard.h"
101 #include "blockinput.h"
102 #include "dispextern.h"
103 #include "composite.h"
104 #include "atimer.h"
105 #include "sysselect.h"
106 #include "syssignal.h"
107 #include "syswait.h"
108 #ifdef HAVE_GNUTLS
109 #include "gnutls.h"
110 #endif
111
112 #if defined (USE_GTK) || defined (HAVE_GCONF)
113 #include "xgselect.h"
114 #endif /* defined (USE_GTK) || defined (HAVE_GCONF) */
115 #ifdef HAVE_NS
116 #include "nsterm.h"
117 #endif
118 extern int timers_run;
119
120 Lisp_Object Qeuid, Qegid, Qcomm, Qstate, Qppid, Qpgrp, Qsess, Qttname, Qtpgid;
121 Lisp_Object Qminflt, Qmajflt, Qcminflt, Qcmajflt, Qutime, Qstime, Qcstime;
122 Lisp_Object Qcutime, Qpri, Qnice, Qthcount, Qstart, Qvsize, Qrss, Qargs;
123 Lisp_Object Quser, Qgroup, Qetime, Qpcpu, Qpmem, Qtime, Qctime;
124 Lisp_Object QCname, QCtype;
125 \f
126 /* Non-zero if keyboard input is on hold, zero otherwise. */
127
128 static int kbd_is_on_hold;
129
130 /* Nonzero means delete a process right away if it exits. */
131 static int delete_exited_processes;
132
133 /* Nonzero means don't run process sentinels. This is used
134 when exiting. */
135 int inhibit_sentinels;
136
137 #ifdef subprocesses
138
139 Lisp_Object Qprocessp;
140 Lisp_Object Qrun, Qstop, Qsignal;
141 Lisp_Object Qopen, Qclosed, Qconnect, Qfailed, Qlisten;
142 Lisp_Object Qlocal, Qipv4, Qdatagram, Qseqpacket;
143 Lisp_Object Qreal, Qnetwork, Qserial;
144 #ifdef AF_INET6
145 Lisp_Object Qipv6;
146 #endif
147 Lisp_Object QCport, QCspeed, QCprocess;
148 Lisp_Object QCbytesize, QCstopbits, QCparity, Qodd, Qeven;
149 Lisp_Object QCflowcontrol, Qhw, Qsw, QCsummary;
150 Lisp_Object QCbuffer, QChost, QCservice;
151 Lisp_Object QClocal, QCremote, QCcoding;
152 Lisp_Object QCserver, QCnowait, QCnoquery, QCstop;
153 Lisp_Object QCsentinel, QClog, QCoptions, QCplist;
154 Lisp_Object Qlast_nonmenu_event;
155 /* QCfamily is declared and initialized in xfaces.c,
156 QCfilter in keyboard.c. */
157 extern Lisp_Object QCfamily, QCfilter;
158
159 /* Qexit is declared and initialized in eval.c. */
160
161 /* QCfamily is defined in xfaces.c. */
162 extern Lisp_Object QCfamily;
163 /* QCfilter is defined in keyboard.c. */
164 extern Lisp_Object QCfilter;
165
166 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
167 #define NETCONN1_P(p) (EQ ((p)->type, Qnetwork))
168 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
169 #define SERIALCONN1_P(p) (EQ ((p)->type, Qserial))
170
171 /* Define first descriptor number available for subprocesses. */
172 #define FIRST_PROC_DESC 3
173
174 /* Define SIGCHLD as an alias for SIGCLD. There are many conditionals
175 testing SIGCHLD. */
176
177 #if !defined (SIGCHLD) && defined (SIGCLD)
178 #define SIGCHLD SIGCLD
179 #endif /* SIGCLD */
180
181 extern const char *get_operating_system_release (void);
182
183 /* From sysdep.c or w32.c */
184 extern int serial_open (char *port);
185 extern void serial_configure (struct Lisp_Process *p, Lisp_Object contact);
186
187 #ifndef HAVE_H_ERRNO
188 extern int h_errno;
189 #endif
190
191 /* t means use pty, nil means use a pipe,
192 maybe other values to come. */
193 static Lisp_Object Vprocess_connection_type;
194
195 /* These next two vars are non-static since sysdep.c uses them in the
196 emulation of `select'. */
197 /* Number of events of change of status of a process. */
198 int process_tick;
199 /* Number of events for which the user or sentinel has been notified. */
200 int update_tick;
201
202 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
203
204 /* Only W32 has this, it really means that select can't take write mask. */
205 #ifdef BROKEN_NON_BLOCKING_CONNECT
206 #undef NON_BLOCKING_CONNECT
207 #define SELECT_CANT_DO_WRITE_MASK
208 #else
209 #ifndef NON_BLOCKING_CONNECT
210 #ifdef HAVE_SELECT
211 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
212 #if defined (O_NONBLOCK) || defined (O_NDELAY)
213 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
214 #define NON_BLOCKING_CONNECT
215 #endif /* EWOULDBLOCK || EINPROGRESS */
216 #endif /* O_NONBLOCK || O_NDELAY */
217 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
218 #endif /* HAVE_SELECT */
219 #endif /* NON_BLOCKING_CONNECT */
220 #endif /* BROKEN_NON_BLOCKING_CONNECT */
221
222 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
223 this system. We need to read full packets, so we need a
224 "non-destructive" select. So we require either native select,
225 or emulation of select using FIONREAD. */
226
227 #ifdef BROKEN_DATAGRAM_SOCKETS
228 #undef DATAGRAM_SOCKETS
229 #else
230 #ifndef DATAGRAM_SOCKETS
231 #if defined (HAVE_SELECT) || defined (FIONREAD)
232 #if defined (HAVE_SENDTO) && defined (HAVE_RECVFROM) && defined (EMSGSIZE)
233 #define DATAGRAM_SOCKETS
234 #endif /* HAVE_SENDTO && HAVE_RECVFROM && EMSGSIZE */
235 #endif /* HAVE_SELECT || FIONREAD */
236 #endif /* DATAGRAM_SOCKETS */
237 #endif /* BROKEN_DATAGRAM_SOCKETS */
238
239 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
240 # define HAVE_SEQPACKET
241 #endif
242
243 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
244 #ifdef EMACS_HAS_USECS
245 #define ADAPTIVE_READ_BUFFERING
246 #endif
247 #endif
248
249 #ifdef ADAPTIVE_READ_BUFFERING
250 #define READ_OUTPUT_DELAY_INCREMENT 10000
251 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
252 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
253
254 /* Number of processes which have a non-zero read_output_delay,
255 and therefore might be delayed for adaptive read buffering. */
256
257 static int process_output_delay_count;
258
259 /* Non-zero if any process has non-nil read_output_skip. */
260
261 static int process_output_skip;
262
263 /* Non-nil means to delay reading process output to improve buffering.
264 A value of t means that delay is reset after each send, any other
265 non-nil value does not reset the delay. A value of nil disables
266 adaptive read buffering completely. */
267 static Lisp_Object Vprocess_adaptive_read_buffering;
268 #else
269 #define process_output_delay_count 0
270 #endif
271
272 static int keyboard_bit_set (SELECT_TYPE *);
273 static void deactivate_process (Lisp_Object);
274 static void status_notify (struct Lisp_Process *);
275 static int read_process_output (Lisp_Object, int);
276 static void create_pty (Lisp_Object);
277
278 /* If we support a window system, turn on the code to poll periodically
279 to detect C-g. It isn't actually used when doing interrupt input. */
280 #ifdef HAVE_WINDOW_SYSTEM
281 #define POLL_FOR_INPUT
282 #endif
283
284 static Lisp_Object get_process (register Lisp_Object name);
285 static void exec_sentinel (Lisp_Object proc, Lisp_Object reason);
286
287 /* Mask of bits indicating the descriptors that we wait for input on. */
288
289 static SELECT_TYPE input_wait_mask;
290
291 /* Mask that excludes keyboard input descriptor(s). */
292
293 static SELECT_TYPE non_keyboard_wait_mask;
294
295 /* Mask that excludes process input descriptor(s). */
296
297 static SELECT_TYPE non_process_wait_mask;
298
299 /* Mask for selecting for write. */
300
301 static SELECT_TYPE write_mask;
302
303 #ifdef NON_BLOCKING_CONNECT
304 /* Mask of bits indicating the descriptors that we wait for connect to
305 complete on. Once they complete, they are removed from this mask
306 and added to the input_wait_mask and non_keyboard_wait_mask. */
307
308 static SELECT_TYPE connect_wait_mask;
309
310 /* Number of bits set in connect_wait_mask. */
311 static int num_pending_connects;
312
313 #define IF_NON_BLOCKING_CONNECT(s) s
314 #else /* NON_BLOCKING_CONNECT */
315 #define IF_NON_BLOCKING_CONNECT(s)
316 #endif /* NON_BLOCKING_CONNECT */
317
318 /* The largest descriptor currently in use for a process object. */
319 static int max_process_desc;
320
321 /* The largest descriptor currently in use for input. */
322 static int max_input_desc;
323
324 /* Indexed by descriptor, gives the process (if any) for that descriptor */
325 Lisp_Object chan_process[MAXDESC];
326
327 /* Alist of elements (NAME . PROCESS) */
328 Lisp_Object Vprocess_alist;
329
330 /* Buffered-ahead input char from process, indexed by channel.
331 -1 means empty (no char is buffered).
332 Used on sys V where the only way to tell if there is any
333 output from the process is to read at least one char.
334 Always -1 on systems that support FIONREAD. */
335
336 /* Don't make static; need to access externally. */
337 int proc_buffered_char[MAXDESC];
338
339 /* Table of `struct coding-system' for each process. */
340 static struct coding_system *proc_decode_coding_system[MAXDESC];
341 static struct coding_system *proc_encode_coding_system[MAXDESC];
342
343 #ifdef DATAGRAM_SOCKETS
344 /* Table of `partner address' for datagram sockets. */
345 struct sockaddr_and_len {
346 struct sockaddr *sa;
347 int len;
348 } datagram_address[MAXDESC];
349 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
350 #define DATAGRAM_CONN_P(proc) (PROCESSP (proc) && datagram_address[XPROCESS (proc)->infd].sa != 0)
351 #else
352 #define DATAGRAM_CHAN_P(chan) (0)
353 #define DATAGRAM_CONN_P(proc) (0)
354 #endif
355
356 /* Maximum number of bytes to send to a pty without an eof. */
357 static int pty_max_bytes;
358
359 #ifdef HAVE_PTYS
360 #ifdef HAVE_PTY_H
361 #include <pty.h>
362 #endif
363 /* The file name of the pty opened by allocate_pty. */
364
365 static char pty_name[24];
366 #endif
367 \f
368
369 struct fd_callback_data
370 {
371 fd_callback func;
372 void *data;
373 #define FOR_READ 1
374 #define FOR_WRITE 2
375 int condition; /* mask of the defines above. */
376 } fd_callback_info[MAXDESC];
377
378
379 /* Add a file descriptor FD to be monitored for when read is possible.
380 When read is possible, call FUNC with argument DATA. */
381
382 void
383 add_read_fd (int fd, fd_callback func, void *data)
384 {
385 xassert (fd < MAXDESC);
386 add_keyboard_wait_descriptor (fd);
387
388 fd_callback_info[fd].func = func;
389 fd_callback_info[fd].data = data;
390 fd_callback_info[fd].condition |= FOR_READ;
391 }
392
393 /* Stop monitoring file descriptor FD for when read is possible. */
394
395 void
396 delete_read_fd (int fd)
397 {
398 xassert (fd < MAXDESC);
399 delete_keyboard_wait_descriptor (fd);
400
401 fd_callback_info[fd].condition &= ~FOR_READ;
402 if (fd_callback_info[fd].condition == 0)
403 {
404 fd_callback_info[fd].func = 0;
405 fd_callback_info[fd].data = 0;
406 }
407 }
408
409 /* Add a file descriptor FD to be monitored for when write is possible.
410 When write is possible, call FUNC with argument DATA. */
411
412 void
413 add_write_fd (int fd, fd_callback func, void *data)
414 {
415 xassert (fd < MAXDESC);
416 FD_SET (fd, &write_mask);
417 if (fd > max_input_desc)
418 max_input_desc = fd;
419
420 fd_callback_info[fd].func = func;
421 fd_callback_info[fd].data = data;
422 fd_callback_info[fd].condition |= FOR_WRITE;
423 }
424
425 /* Stop monitoring file descriptor FD for when write is possible. */
426
427 void
428 delete_write_fd (int fd)
429 {
430 int lim = max_input_desc;
431
432 xassert (fd < MAXDESC);
433 FD_CLR (fd, &write_mask);
434 fd_callback_info[fd].condition &= ~FOR_WRITE;
435 if (fd_callback_info[fd].condition == 0)
436 {
437 fd_callback_info[fd].func = 0;
438 fd_callback_info[fd].data = 0;
439
440 if (fd == max_input_desc)
441 for (fd = lim; fd >= 0; fd--)
442 if (FD_ISSET (fd, &input_wait_mask) || FD_ISSET (fd, &write_mask))
443 {
444 max_input_desc = fd;
445 break;
446 }
447
448 }
449 }
450
451 \f
452 /* Compute the Lisp form of the process status, p->status, from
453 the numeric status that was returned by `wait'. */
454
455 static Lisp_Object status_convert (int);
456
457 static void
458 update_status (struct Lisp_Process *p)
459 {
460 eassert (p->raw_status_new);
461 p->status = status_convert (p->raw_status);
462 p->raw_status_new = 0;
463 }
464
465 /* Convert a process status word in Unix format to
466 the list that we use internally. */
467
468 static Lisp_Object
469 status_convert (int w)
470 {
471 if (WIFSTOPPED (w))
472 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
473 else if (WIFEXITED (w))
474 return Fcons (Qexit, Fcons (make_number (WRETCODE (w)),
475 WCOREDUMP (w) ? Qt : Qnil));
476 else if (WIFSIGNALED (w))
477 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
478 WCOREDUMP (w) ? Qt : Qnil));
479 else
480 return Qrun;
481 }
482
483 /* Given a status-list, extract the three pieces of information
484 and store them individually through the three pointers. */
485
486 static void
487 decode_status (Lisp_Object l, Lisp_Object *symbol, int *code, int *coredump)
488 {
489 Lisp_Object tem;
490
491 if (SYMBOLP (l))
492 {
493 *symbol = l;
494 *code = 0;
495 *coredump = 0;
496 }
497 else
498 {
499 *symbol = XCAR (l);
500 tem = XCDR (l);
501 *code = XFASTINT (XCAR (tem));
502 tem = XCDR (tem);
503 *coredump = !NILP (tem);
504 }
505 }
506
507 /* Return a string describing a process status list. */
508
509 static Lisp_Object
510 status_message (struct Lisp_Process *p)
511 {
512 Lisp_Object status = p->status;
513 Lisp_Object symbol;
514 int code, coredump;
515 Lisp_Object string, string2;
516
517 decode_status (status, &symbol, &code, &coredump);
518
519 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
520 {
521 char *signame;
522 synchronize_system_messages_locale ();
523 signame = strsignal (code);
524 if (signame == 0)
525 string = build_string ("unknown");
526 else
527 {
528 int c1, c2;
529
530 string = make_unibyte_string (signame, strlen (signame));
531 if (! NILP (Vlocale_coding_system))
532 string = (code_convert_string_norecord
533 (string, Vlocale_coding_system, 0));
534 c1 = STRING_CHAR ((char *) SDATA (string));
535 c2 = DOWNCASE (c1);
536 if (c1 != c2)
537 Faset (string, make_number (0), make_number (c2));
538 }
539 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
540 return concat2 (string, string2);
541 }
542 else if (EQ (symbol, Qexit))
543 {
544 if (NETCONN1_P (p))
545 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
546 if (code == 0)
547 return build_string ("finished\n");
548 string = Fnumber_to_string (make_number (code));
549 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
550 return concat3 (build_string ("exited abnormally with code "),
551 string, string2);
552 }
553 else if (EQ (symbol, Qfailed))
554 {
555 string = Fnumber_to_string (make_number (code));
556 string2 = build_string ("\n");
557 return concat3 (build_string ("failed with code "),
558 string, string2);
559 }
560 else
561 return Fcopy_sequence (Fsymbol_name (symbol));
562 }
563 \f
564 #ifdef HAVE_PTYS
565
566 /* Open an available pty, returning a file descriptor.
567 Return -1 on failure.
568 The file name of the terminal corresponding to the pty
569 is left in the variable pty_name. */
570
571 static int
572 allocate_pty (void)
573 {
574 register int c, i;
575 int fd;
576
577 #ifdef PTY_ITERATION
578 PTY_ITERATION
579 #else
580 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
581 for (i = 0; i < 16; i++)
582 #endif
583 {
584 struct stat stb; /* Used in some PTY_OPEN. */
585 #ifdef PTY_NAME_SPRINTF
586 PTY_NAME_SPRINTF
587 #else
588 sprintf (pty_name, "/dev/pty%c%x", c, i);
589 #endif /* no PTY_NAME_SPRINTF */
590
591 #ifdef PTY_OPEN
592 PTY_OPEN;
593 #else /* no PTY_OPEN */
594 {
595 { /* Some systems name their pseudoterminals so that there are gaps in
596 the usual sequence - for example, on HP9000/S700 systems, there
597 are no pseudoterminals with names ending in 'f'. So we wait for
598 three failures in a row before deciding that we've reached the
599 end of the ptys. */
600 int failed_count = 0;
601
602 if (stat (pty_name, &stb) < 0)
603 {
604 failed_count++;
605 if (failed_count >= 3)
606 return -1;
607 }
608 else
609 failed_count = 0;
610 }
611 # ifdef O_NONBLOCK
612 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
613 # else
614 fd = emacs_open (pty_name, O_RDWR | O_NDELAY, 0);
615 # endif
616 }
617 #endif /* no PTY_OPEN */
618
619 if (fd >= 0)
620 {
621 /* check to make certain that both sides are available
622 this avoids a nasty yet stupid bug in rlogins */
623 #ifdef PTY_TTY_NAME_SPRINTF
624 PTY_TTY_NAME_SPRINTF
625 #else
626 sprintf (pty_name, "/dev/tty%c%x", c, i);
627 #endif /* no PTY_TTY_NAME_SPRINTF */
628 if (access (pty_name, 6) != 0)
629 {
630 emacs_close (fd);
631 # ifndef __sgi
632 continue;
633 # else
634 return -1;
635 # endif /* __sgi */
636 }
637 setup_pty (fd);
638 return fd;
639 }
640 }
641 return -1;
642 }
643 #endif /* HAVE_PTYS */
644 \f
645 static Lisp_Object
646 make_process (Lisp_Object name)
647 {
648 register Lisp_Object val, tem, name1;
649 register struct Lisp_Process *p;
650 char suffix[10];
651 register int i;
652
653 p = allocate_process ();
654
655 p->infd = -1;
656 p->outfd = -1;
657 p->tick = 0;
658 p->update_tick = 0;
659 p->pid = 0;
660 p->pty_flag = 0;
661 p->raw_status_new = 0;
662 p->status = Qrun;
663 p->mark = Fmake_marker ();
664 p->kill_without_query = 0;
665
666 #ifdef ADAPTIVE_READ_BUFFERING
667 p->adaptive_read_buffering = 0;
668 p->read_output_delay = 0;
669 p->read_output_skip = 0;
670 #endif
671
672 #ifdef HAVE_GNUTLS
673 p->gnutls_initstage = GNUTLS_STAGE_EMPTY;
674 p->gnutls_log_level = 0;
675 #endif
676
677 /* If name is already in use, modify it until it is unused. */
678
679 name1 = name;
680 for (i = 1; ; i++)
681 {
682 tem = Fget_process (name1);
683 if (NILP (tem)) break;
684 sprintf (suffix, "<%d>", i);
685 name1 = concat2 (name, build_string (suffix));
686 }
687 name = name1;
688 p->name = name;
689 XSETPROCESS (val, p);
690 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
691 return val;
692 }
693
694 static void
695 remove_process (register Lisp_Object proc)
696 {
697 register Lisp_Object pair;
698
699 pair = Frassq (proc, Vprocess_alist);
700 Vprocess_alist = Fdelq (pair, Vprocess_alist);
701
702 deactivate_process (proc);
703 }
704
705 \f
706 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
707 doc: /* Return t if OBJECT is a process. */)
708 (Lisp_Object object)
709 {
710 return PROCESSP (object) ? Qt : Qnil;
711 }
712
713 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
714 doc: /* Return the process named NAME, or nil if there is none. */)
715 (register Lisp_Object name)
716 {
717 if (PROCESSP (name))
718 return name;
719 CHECK_STRING (name);
720 return Fcdr (Fassoc (name, Vprocess_alist));
721 }
722
723 /* This is how commands for the user decode process arguments. It
724 accepts a process, a process name, a buffer, a buffer name, or nil.
725 Buffers denote the first process in the buffer, and nil denotes the
726 current buffer. */
727
728 static Lisp_Object
729 get_process (register Lisp_Object name)
730 {
731 register Lisp_Object proc, obj;
732 if (STRINGP (name))
733 {
734 obj = Fget_process (name);
735 if (NILP (obj))
736 obj = Fget_buffer (name);
737 if (NILP (obj))
738 error ("Process %s does not exist", SDATA (name));
739 }
740 else if (NILP (name))
741 obj = Fcurrent_buffer ();
742 else
743 obj = name;
744
745 /* Now obj should be either a buffer object or a process object.
746 */
747 if (BUFFERP (obj))
748 {
749 proc = Fget_buffer_process (obj);
750 if (NILP (proc))
751 error ("Buffer %s has no process", SDATA (XBUFFER (obj)->name));
752 }
753 else
754 {
755 CHECK_PROCESS (obj);
756 proc = obj;
757 }
758 return proc;
759 }
760
761
762 #ifdef SIGCHLD
763 /* Fdelete_process promises to immediately forget about the process, but in
764 reality, Emacs needs to remember those processes until they have been
765 treated by sigchld_handler; otherwise this handler would consider the
766 process as being synchronous and say that the synchronous process is
767 dead. */
768 static Lisp_Object deleted_pid_list;
769 #endif
770
771 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
772 doc: /* Delete PROCESS: kill it and forget about it immediately.
773 PROCESS may be a process, a buffer, the name of a process or buffer, or
774 nil, indicating the current buffer's process. */)
775 (register Lisp_Object process)
776 {
777 register struct Lisp_Process *p;
778
779 process = get_process (process);
780 p = XPROCESS (process);
781
782 p->raw_status_new = 0;
783 if (NETCONN1_P (p) || SERIALCONN1_P (p))
784 {
785 p->status = Fcons (Qexit, Fcons (make_number (0), Qnil));
786 p->tick = ++process_tick;
787 status_notify (p);
788 redisplay_preserve_echo_area (13);
789 }
790 else if (p->infd >= 0)
791 {
792 #ifdef SIGCHLD
793 Lisp_Object symbol;
794 /* Assignment to EMACS_INT stops GCC whining about limited range
795 of data type. */
796 EMACS_INT pid = p->pid;
797
798 /* No problem storing the pid here, as it is still in Vprocess_alist. */
799 deleted_pid_list = Fcons (make_fixnum_or_float (pid),
800 /* GC treated elements set to nil. */
801 Fdelq (Qnil, deleted_pid_list));
802 /* If the process has already signaled, remove it from the list. */
803 if (p->raw_status_new)
804 update_status (p);
805 symbol = p->status;
806 if (CONSP (p->status))
807 symbol = XCAR (p->status);
808 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit))
809 deleted_pid_list
810 = Fdelete (make_fixnum_or_float (pid), deleted_pid_list);
811 else
812 #endif
813 {
814 Fkill_process (process, Qnil);
815 /* Do this now, since remove_process will make sigchld_handler do nothing. */
816 p->status
817 = Fcons (Qsignal, Fcons (make_number (SIGKILL), Qnil));
818 p->tick = ++process_tick;
819 status_notify (p);
820 redisplay_preserve_echo_area (13);
821 }
822 }
823 remove_process (process);
824 return Qnil;
825 }
826 \f
827 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
828 doc: /* Return the status of PROCESS.
829 The returned value is one of the following symbols:
830 run -- for a process that is running.
831 stop -- for a process stopped but continuable.
832 exit -- for a process that has exited.
833 signal -- for a process that has got a fatal signal.
834 open -- for a network stream connection that is open.
835 listen -- for a network stream server that is listening.
836 closed -- for a network stream connection that is closed.
837 connect -- when waiting for a non-blocking connection to complete.
838 failed -- when a non-blocking connection has failed.
839 nil -- if arg is a process name and no such process exists.
840 PROCESS may be a process, a buffer, the name of a process, or
841 nil, indicating the current buffer's process. */)
842 (register Lisp_Object process)
843 {
844 register struct Lisp_Process *p;
845 register Lisp_Object status;
846
847 if (STRINGP (process))
848 process = Fget_process (process);
849 else
850 process = get_process (process);
851
852 if (NILP (process))
853 return process;
854
855 p = XPROCESS (process);
856 if (p->raw_status_new)
857 update_status (p);
858 status = p->status;
859 if (CONSP (status))
860 status = XCAR (status);
861 if (NETCONN1_P (p) || SERIALCONN1_P (p))
862 {
863 if (EQ (status, Qexit))
864 status = Qclosed;
865 else if (EQ (p->command, Qt))
866 status = Qstop;
867 else if (EQ (status, Qrun))
868 status = Qopen;
869 }
870 return status;
871 }
872
873 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
874 1, 1, 0,
875 doc: /* Return the exit status of PROCESS or the signal number that killed it.
876 If PROCESS has not yet exited or died, return 0. */)
877 (register Lisp_Object process)
878 {
879 CHECK_PROCESS (process);
880 if (XPROCESS (process)->raw_status_new)
881 update_status (XPROCESS (process));
882 if (CONSP (XPROCESS (process)->status))
883 return XCAR (XCDR (XPROCESS (process)->status));
884 return make_number (0);
885 }
886
887 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
888 doc: /* Return the process id of PROCESS.
889 This is the pid of the external process which PROCESS uses or talks to.
890 For a network connection, this value is nil. */)
891 (register Lisp_Object process)
892 {
893 /* Assignment to EMACS_INT stops GCC whining about limited range of
894 data type. */
895 EMACS_INT pid;
896
897 CHECK_PROCESS (process);
898 pid = XPROCESS (process)->pid;
899 return (pid ? make_fixnum_or_float (pid) : Qnil);
900 }
901
902 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
903 doc: /* Return the name of PROCESS, as a string.
904 This is the name of the program invoked in PROCESS,
905 possibly modified to make it unique among process names. */)
906 (register Lisp_Object process)
907 {
908 CHECK_PROCESS (process);
909 return XPROCESS (process)->name;
910 }
911
912 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
913 doc: /* Return the command that was executed to start PROCESS.
914 This is a list of strings, the first string being the program executed
915 and the rest of the strings being the arguments given to it.
916 For a network or serial process, this is nil (process is running) or t
917 \(process is stopped). */)
918 (register Lisp_Object process)
919 {
920 CHECK_PROCESS (process);
921 return XPROCESS (process)->command;
922 }
923
924 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
925 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
926 This is the terminal that the process itself reads and writes on,
927 not the name of the pty that Emacs uses to talk with that terminal. */)
928 (register Lisp_Object process)
929 {
930 CHECK_PROCESS (process);
931 return XPROCESS (process)->tty_name;
932 }
933
934 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
935 2, 2, 0,
936 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil). */)
937 (register Lisp_Object process, Lisp_Object buffer)
938 {
939 struct Lisp_Process *p;
940
941 CHECK_PROCESS (process);
942 if (!NILP (buffer))
943 CHECK_BUFFER (buffer);
944 p = XPROCESS (process);
945 p->buffer = buffer;
946 if (NETCONN1_P (p) || SERIALCONN1_P (p))
947 p->childp = Fplist_put (p->childp, QCbuffer, buffer);
948 setup_process_coding_systems (process);
949 return buffer;
950 }
951
952 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
953 1, 1, 0,
954 doc: /* Return the buffer PROCESS is associated with.
955 Output from PROCESS is inserted in this buffer unless PROCESS has a filter. */)
956 (register Lisp_Object process)
957 {
958 CHECK_PROCESS (process);
959 return XPROCESS (process)->buffer;
960 }
961
962 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
963 1, 1, 0,
964 doc: /* Return the marker for the end of the last output from PROCESS. */)
965 (register Lisp_Object process)
966 {
967 CHECK_PROCESS (process);
968 return XPROCESS (process)->mark;
969 }
970
971 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
972 2, 2, 0,
973 doc: /* Give PROCESS the filter function FILTER; nil means no filter.
974 A value of t means stop accepting output from the process.
975
976 When a process has a filter, its buffer is not used for output.
977 Instead, each time it does output, the entire string of output is
978 passed to the filter.
979
980 The filter gets two arguments: the process and the string of output.
981 The string argument is normally a multibyte string, except:
982 - if the process' input coding system is no-conversion or raw-text,
983 it is a unibyte string (the non-converted input), or else
984 - if `default-enable-multibyte-characters' is nil, it is a unibyte
985 string (the result of converting the decoded input multibyte
986 string to unibyte with `string-make-unibyte'). */)
987 (register Lisp_Object process, Lisp_Object filter)
988 {
989 struct Lisp_Process *p;
990
991 CHECK_PROCESS (process);
992 p = XPROCESS (process);
993
994 /* Don't signal an error if the process' input file descriptor
995 is closed. This could make debugging Lisp more difficult,
996 for example when doing something like
997
998 (setq process (start-process ...))
999 (debug)
1000 (set-process-filter process ...) */
1001
1002 if (p->infd >= 0)
1003 {
1004 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
1005 {
1006 FD_CLR (p->infd, &input_wait_mask);
1007 FD_CLR (p->infd, &non_keyboard_wait_mask);
1008 }
1009 else if (EQ (p->filter, Qt)
1010 /* Network or serial process not stopped: */
1011 && !EQ (p->command, Qt))
1012 {
1013 FD_SET (p->infd, &input_wait_mask);
1014 FD_SET (p->infd, &non_keyboard_wait_mask);
1015 }
1016 }
1017
1018 p->filter = filter;
1019 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1020 p->childp = Fplist_put (p->childp, QCfilter, filter);
1021 setup_process_coding_systems (process);
1022 return filter;
1023 }
1024
1025 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1026 1, 1, 0,
1027 doc: /* Returns the filter function of PROCESS; nil if none.
1028 See `set-process-filter' for more info on filter functions. */)
1029 (register Lisp_Object process)
1030 {
1031 CHECK_PROCESS (process);
1032 return XPROCESS (process)->filter;
1033 }
1034
1035 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1036 2, 2, 0,
1037 doc: /* Give PROCESS the sentinel SENTINEL; nil for none.
1038 The sentinel is called as a function when the process changes state.
1039 It gets two arguments: the process, and a string describing the change. */)
1040 (register Lisp_Object process, Lisp_Object sentinel)
1041 {
1042 struct Lisp_Process *p;
1043
1044 CHECK_PROCESS (process);
1045 p = XPROCESS (process);
1046
1047 p->sentinel = sentinel;
1048 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1049 p->childp = Fplist_put (p->childp, QCsentinel, sentinel);
1050 return sentinel;
1051 }
1052
1053 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1054 1, 1, 0,
1055 doc: /* Return the sentinel of PROCESS; nil if none.
1056 See `set-process-sentinel' for more info on sentinels. */)
1057 (register Lisp_Object process)
1058 {
1059 CHECK_PROCESS (process);
1060 return XPROCESS (process)->sentinel;
1061 }
1062
1063 DEFUN ("set-process-window-size", Fset_process_window_size,
1064 Sset_process_window_size, 3, 3, 0,
1065 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1066 (register Lisp_Object process, Lisp_Object height, Lisp_Object width)
1067 {
1068 CHECK_PROCESS (process);
1069 CHECK_NATNUM (height);
1070 CHECK_NATNUM (width);
1071
1072 if (XPROCESS (process)->infd < 0
1073 || set_window_size (XPROCESS (process)->infd,
1074 XINT (height), XINT (width)) <= 0)
1075 return Qnil;
1076 else
1077 return Qt;
1078 }
1079
1080 DEFUN ("set-process-inherit-coding-system-flag",
1081 Fset_process_inherit_coding_system_flag,
1082 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1083 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1084 If the second argument FLAG is non-nil, then the variable
1085 `buffer-file-coding-system' of the buffer associated with PROCESS
1086 will be bound to the value of the coding system used to decode
1087 the process output.
1088
1089 This is useful when the coding system specified for the process buffer
1090 leaves either the character code conversion or the end-of-line conversion
1091 unspecified, or if the coding system used to decode the process output
1092 is more appropriate for saving the process buffer.
1093
1094 Binding the variable `inherit-process-coding-system' to non-nil before
1095 starting the process is an alternative way of setting the inherit flag
1096 for the process which will run. */)
1097 (register Lisp_Object process, Lisp_Object flag)
1098 {
1099 CHECK_PROCESS (process);
1100 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1101 return flag;
1102 }
1103
1104 DEFUN ("set-process-query-on-exit-flag",
1105 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1106 2, 2, 0,
1107 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1108 If the second argument FLAG is non-nil, Emacs will query the user before
1109 exiting or killing a buffer if PROCESS is running. */)
1110 (register Lisp_Object process, Lisp_Object flag)
1111 {
1112 CHECK_PROCESS (process);
1113 XPROCESS (process)->kill_without_query = NILP (flag);
1114 return flag;
1115 }
1116
1117 DEFUN ("process-query-on-exit-flag",
1118 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1119 1, 1, 0,
1120 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1121 (register Lisp_Object process)
1122 {
1123 CHECK_PROCESS (process);
1124 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1125 }
1126
1127 #ifdef DATAGRAM_SOCKETS
1128 Lisp_Object Fprocess_datagram_address (Lisp_Object process);
1129 #endif
1130
1131 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1132 1, 2, 0,
1133 doc: /* Return the contact info of PROCESS; t for a real child.
1134 For a network or serial connection, the value depends on the optional
1135 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1136 SERVICE) for a network connection or (PORT SPEED) for a serial
1137 connection. If KEY is t, the complete contact information for the
1138 connection is returned, else the specific value for the keyword KEY is
1139 returned. See `make-network-process' or `make-serial-process' for a
1140 list of keywords. */)
1141 (register Lisp_Object process, Lisp_Object key)
1142 {
1143 Lisp_Object contact;
1144
1145 CHECK_PROCESS (process);
1146 contact = XPROCESS (process)->childp;
1147
1148 #ifdef DATAGRAM_SOCKETS
1149 if (DATAGRAM_CONN_P (process)
1150 && (EQ (key, Qt) || EQ (key, QCremote)))
1151 contact = Fplist_put (contact, QCremote,
1152 Fprocess_datagram_address (process));
1153 #endif
1154
1155 if ((!NETCONN_P (process) && !SERIALCONN_P (process)) || EQ (key, Qt))
1156 return contact;
1157 if (NILP (key) && NETCONN_P (process))
1158 return Fcons (Fplist_get (contact, QChost),
1159 Fcons (Fplist_get (contact, QCservice), Qnil));
1160 if (NILP (key) && SERIALCONN_P (process))
1161 return Fcons (Fplist_get (contact, QCport),
1162 Fcons (Fplist_get (contact, QCspeed), Qnil));
1163 return Fplist_get (contact, key);
1164 }
1165
1166 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1167 1, 1, 0,
1168 doc: /* Return the plist of PROCESS. */)
1169 (register Lisp_Object process)
1170 {
1171 CHECK_PROCESS (process);
1172 return XPROCESS (process)->plist;
1173 }
1174
1175 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1176 2, 2, 0,
1177 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1178 (register Lisp_Object process, Lisp_Object plist)
1179 {
1180 CHECK_PROCESS (process);
1181 CHECK_LIST (plist);
1182
1183 XPROCESS (process)->plist = plist;
1184 return plist;
1185 }
1186
1187 #if 0 /* Turned off because we don't currently record this info
1188 in the process. Perhaps add it. */
1189 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1190 doc: /* Return the connection type of PROCESS.
1191 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1192 a socket connection. */)
1193 (Lisp_Object process)
1194 {
1195 return XPROCESS (process)->type;
1196 }
1197 #endif
1198
1199 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1200 doc: /* Return the connection type of PROCESS.
1201 The value is either the symbol `real', `network', or `serial'.
1202 PROCESS may be a process, a buffer, the name of a process or buffer, or
1203 nil, indicating the current buffer's process. */)
1204 (Lisp_Object process)
1205 {
1206 Lisp_Object proc;
1207 proc = get_process (process);
1208 return XPROCESS (proc)->type;
1209 }
1210
1211 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1212 1, 2, 0,
1213 doc: /* Convert network ADDRESS from internal format to a string.
1214 A 4 or 5 element vector represents an IPv4 address (with port number).
1215 An 8 or 9 element vector represents an IPv6 address (with port number).
1216 If optional second argument OMIT-PORT is non-nil, don't include a port
1217 number in the string, even when present in ADDRESS.
1218 Returns nil if format of ADDRESS is invalid. */)
1219 (Lisp_Object address, Lisp_Object omit_port)
1220 {
1221 if (NILP (address))
1222 return Qnil;
1223
1224 if (STRINGP (address)) /* AF_LOCAL */
1225 return address;
1226
1227 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1228 {
1229 register struct Lisp_Vector *p = XVECTOR (address);
1230 Lisp_Object args[10];
1231 int nargs, i;
1232
1233 if (p->size == 4 || (p->size == 5 && !NILP (omit_port)))
1234 {
1235 args[0] = build_string ("%d.%d.%d.%d");
1236 nargs = 4;
1237 }
1238 else if (p->size == 5)
1239 {
1240 args[0] = build_string ("%d.%d.%d.%d:%d");
1241 nargs = 5;
1242 }
1243 else if (p->size == 8 || (p->size == 9 && !NILP (omit_port)))
1244 {
1245 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
1246 nargs = 8;
1247 }
1248 else if (p->size == 9)
1249 {
1250 args[0] = build_string ("[%x:%x:%x:%x:%x:%x:%x:%x]:%d");
1251 nargs = 9;
1252 }
1253 else
1254 return Qnil;
1255
1256 for (i = 0; i < nargs; i++)
1257 {
1258 EMACS_INT element = XINT (p->contents[i]);
1259
1260 if (element < 0 || element > 65535)
1261 return Qnil;
1262
1263 if (nargs <= 5 /* IPv4 */
1264 && i < 4 /* host, not port */
1265 && element > 255)
1266 return Qnil;
1267
1268 args[i+1] = p->contents[i];
1269 }
1270
1271 return Fformat (nargs+1, args);
1272 }
1273
1274 if (CONSP (address))
1275 {
1276 Lisp_Object args[2];
1277 args[0] = build_string ("<Family %d>");
1278 args[1] = Fcar (address);
1279 return Fformat (2, args);
1280 }
1281
1282 return Qnil;
1283 }
1284 \f
1285 static Lisp_Object
1286 list_processes_1 (Lisp_Object query_only)
1287 {
1288 register Lisp_Object tail, tem;
1289 Lisp_Object proc, minspace, tem1;
1290 register struct Lisp_Process *p;
1291 char tembuf[300];
1292 int w_proc, w_buffer, w_tty;
1293 int exited = 0;
1294 Lisp_Object i_status, i_buffer, i_tty, i_command;
1295
1296 w_proc = 4; /* Proc */
1297 w_buffer = 6; /* Buffer */
1298 w_tty = 0; /* Omit if no ttys */
1299
1300 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
1301 {
1302 int i;
1303
1304 proc = Fcdr (XCAR (tail));
1305 p = XPROCESS (proc);
1306 if (NILP (p->type))
1307 continue;
1308 if (!NILP (query_only) && p->kill_without_query)
1309 continue;
1310 if (STRINGP (p->name)
1311 && ( i = SCHARS (p->name), (i > w_proc)))
1312 w_proc = i;
1313 if (!NILP (p->buffer))
1314 {
1315 if (NILP (XBUFFER (p->buffer)->name))
1316 {
1317 if (w_buffer < 8)
1318 w_buffer = 8; /* (Killed) */
1319 }
1320 else if ((i = SCHARS (XBUFFER (p->buffer)->name), (i > w_buffer)))
1321 w_buffer = i;
1322 }
1323 if (STRINGP (p->tty_name)
1324 && (i = SCHARS (p->tty_name), (i > w_tty)))
1325 w_tty = i;
1326 }
1327
1328 XSETFASTINT (i_status, w_proc + 1);
1329 XSETFASTINT (i_buffer, XFASTINT (i_status) + 9);
1330 if (w_tty)
1331 {
1332 XSETFASTINT (i_tty, XFASTINT (i_buffer) + w_buffer + 1);
1333 XSETFASTINT (i_command, XFASTINT (i_tty) + w_tty + 1);
1334 }
1335 else
1336 {
1337 i_tty = Qnil;
1338 XSETFASTINT (i_command, XFASTINT (i_buffer) + w_buffer + 1);
1339 }
1340
1341 XSETFASTINT (minspace, 1);
1342
1343 set_buffer_internal (XBUFFER (Vstandard_output));
1344 current_buffer->undo_list = Qt;
1345
1346 current_buffer->truncate_lines = Qt;
1347
1348 write_string ("Proc", -1);
1349 Findent_to (i_status, minspace); write_string ("Status", -1);
1350 Findent_to (i_buffer, minspace); write_string ("Buffer", -1);
1351 if (!NILP (i_tty))
1352 {
1353 Findent_to (i_tty, minspace); write_string ("Tty", -1);
1354 }
1355 Findent_to (i_command, minspace); write_string ("Command", -1);
1356 write_string ("\n", -1);
1357
1358 write_string ("----", -1);
1359 Findent_to (i_status, minspace); write_string ("------", -1);
1360 Findent_to (i_buffer, minspace); write_string ("------", -1);
1361 if (!NILP (i_tty))
1362 {
1363 Findent_to (i_tty, minspace); write_string ("---", -1);
1364 }
1365 Findent_to (i_command, minspace); write_string ("-------", -1);
1366 write_string ("\n", -1);
1367
1368 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
1369 {
1370 Lisp_Object symbol;
1371
1372 proc = Fcdr (XCAR (tail));
1373 p = XPROCESS (proc);
1374 if (NILP (p->type))
1375 continue;
1376 if (!NILP (query_only) && p->kill_without_query)
1377 continue;
1378
1379 Finsert (1, &p->name);
1380 Findent_to (i_status, minspace);
1381
1382 if (p->raw_status_new)
1383 update_status (p);
1384 symbol = p->status;
1385 if (CONSP (p->status))
1386 symbol = XCAR (p->status);
1387
1388 if (EQ (symbol, Qsignal))
1389 {
1390 Lisp_Object tem;
1391 tem = Fcar (Fcdr (p->status));
1392 Fprinc (symbol, Qnil);
1393 }
1394 else if (NETCONN1_P (p) || SERIALCONN1_P (p))
1395 {
1396 if (EQ (symbol, Qexit))
1397 write_string ("closed", -1);
1398 else if (EQ (p->command, Qt))
1399 write_string ("stopped", -1);
1400 else if (EQ (symbol, Qrun))
1401 write_string ("open", -1);
1402 else
1403 Fprinc (symbol, Qnil);
1404 }
1405 else if (SERIALCONN1_P (p))
1406 {
1407 write_string ("running", -1);
1408 }
1409 else
1410 Fprinc (symbol, Qnil);
1411
1412 if (EQ (symbol, Qexit))
1413 {
1414 Lisp_Object tem;
1415 tem = Fcar (Fcdr (p->status));
1416 if (XFASTINT (tem))
1417 {
1418 sprintf (tembuf, " %d", (int) XFASTINT (tem));
1419 write_string (tembuf, -1);
1420 }
1421 }
1422
1423 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit) || EQ (symbol, Qclosed))
1424 exited++;
1425
1426 Findent_to (i_buffer, minspace);
1427 if (NILP (p->buffer))
1428 insert_string ("(none)");
1429 else if (NILP (XBUFFER (p->buffer)->name))
1430 insert_string ("(Killed)");
1431 else
1432 Finsert (1, &XBUFFER (p->buffer)->name);
1433
1434 if (!NILP (i_tty))
1435 {
1436 Findent_to (i_tty, minspace);
1437 if (STRINGP (p->tty_name))
1438 Finsert (1, &p->tty_name);
1439 }
1440
1441 Findent_to (i_command, minspace);
1442
1443 if (EQ (p->status, Qlisten))
1444 {
1445 Lisp_Object port = Fplist_get (p->childp, QCservice);
1446 if (INTEGERP (port))
1447 port = Fnumber_to_string (port);
1448 if (NILP (port))
1449 port = Fformat_network_address (Fplist_get (p->childp, QClocal), Qnil);
1450 sprintf (tembuf, "(network %s server on %s)\n",
1451 (DATAGRAM_CHAN_P (p->infd) ? "datagram" : "stream"),
1452 (STRINGP (port) ? (char *)SDATA (port) : "?"));
1453 insert_string (tembuf);
1454 }
1455 else if (NETCONN1_P (p))
1456 {
1457 /* For a local socket, there is no host name,
1458 so display service instead. */
1459 Lisp_Object host = Fplist_get (p->childp, QChost);
1460 if (!STRINGP (host))
1461 {
1462 host = Fplist_get (p->childp, QCservice);
1463 if (INTEGERP (host))
1464 host = Fnumber_to_string (host);
1465 }
1466 if (NILP (host))
1467 host = Fformat_network_address (Fplist_get (p->childp, QCremote), Qnil);
1468 sprintf (tembuf, "(network %s connection to %s)\n",
1469 (DATAGRAM_CHAN_P (p->infd) ? "datagram" : "stream"),
1470 (STRINGP (host) ? (char *)SDATA (host) : "?"));
1471 insert_string (tembuf);
1472 }
1473 else if (SERIALCONN1_P (p))
1474 {
1475 Lisp_Object port = Fplist_get (p->childp, QCport);
1476 Lisp_Object speed = Fplist_get (p->childp, QCspeed);
1477 insert_string ("(serial port ");
1478 if (STRINGP (port))
1479 insert_string (SDATA (port));
1480 else
1481 insert_string ("?");
1482 if (INTEGERP (speed))
1483 {
1484 sprintf (tembuf, " at %ld b/s", (long) XINT (speed));
1485 insert_string (tembuf);
1486 }
1487 insert_string (")\n");
1488 }
1489 else
1490 {
1491 tem = p->command;
1492 while (1)
1493 {
1494 tem1 = Fcar (tem);
1495 if (NILP (tem1))
1496 break;
1497 Finsert (1, &tem1);
1498 tem = Fcdr (tem);
1499 if (NILP (tem))
1500 break;
1501 insert_string (" ");
1502 }
1503 insert_string ("\n");
1504 }
1505 }
1506 if (exited)
1507 {
1508 status_notify (NULL);
1509 redisplay_preserve_echo_area (13);
1510 }
1511 return Qnil;
1512 }
1513
1514 DEFUN ("list-processes", Flist_processes, Slist_processes, 0, 1, "P",
1515 doc: /* Display a list of all processes.
1516 If optional argument QUERY-ONLY is non-nil, only processes with
1517 the query-on-exit flag set will be listed.
1518 Any process listed as exited or signaled is actually eliminated
1519 after the listing is made. */)
1520 (Lisp_Object query_only)
1521 {
1522 internal_with_output_to_temp_buffer ("*Process List*",
1523 list_processes_1, query_only);
1524 return Qnil;
1525 }
1526
1527 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1528 doc: /* Return a list of all processes. */)
1529 (void)
1530 {
1531 return Fmapcar (Qcdr, Vprocess_alist);
1532 }
1533 \f
1534 /* Starting asynchronous inferior processes. */
1535
1536 static Lisp_Object start_process_unwind (Lisp_Object proc);
1537
1538 DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
1539 doc: /* Start a program in a subprocess. Return the process object for it.
1540 NAME is name for process. It is modified if necessary to make it unique.
1541 BUFFER is the buffer (or buffer name) to associate with the process.
1542
1543 Process output (both standard output and standard error streams) goes
1544 at end of BUFFER, unless you specify an output stream or filter
1545 function to handle the output. BUFFER may also be nil, meaning that
1546 this process is not associated with any buffer.
1547
1548 PROGRAM is the program file name. It is searched for in PATH. If
1549 nil, just associate a pty with the buffer. Remaining arguments are
1550 strings to give program as arguments.
1551
1552 If you want to separate standard output from standard error, invoke
1553 the command through a shell and redirect one of them using the shell
1554 syntax.
1555
1556 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1557 (int nargs, register Lisp_Object *args)
1558 {
1559 Lisp_Object buffer, name, program, proc, current_dir, tem;
1560 register unsigned char **new_argv;
1561 register int i;
1562 int count = SPECPDL_INDEX ();
1563
1564 buffer = args[1];
1565 if (!NILP (buffer))
1566 buffer = Fget_buffer_create (buffer);
1567
1568 /* Make sure that the child will be able to chdir to the current
1569 buffer's current directory, or its unhandled equivalent. We
1570 can't just have the child check for an error when it does the
1571 chdir, since it's in a vfork.
1572
1573 We have to GCPRO around this because Fexpand_file_name and
1574 Funhandled_file_name_directory might call a file name handling
1575 function. The argument list is protected by the caller, so all
1576 we really have to worry about is buffer. */
1577 {
1578 struct gcpro gcpro1, gcpro2;
1579
1580 current_dir = current_buffer->directory;
1581
1582 GCPRO2 (buffer, current_dir);
1583
1584 current_dir = Funhandled_file_name_directory (current_dir);
1585 if (NILP (current_dir))
1586 /* If the file name handler says that current_dir is unreachable, use
1587 a sensible default. */
1588 current_dir = build_string ("~/");
1589 current_dir = expand_and_dir_to_file (current_dir, Qnil);
1590 if (NILP (Ffile_accessible_directory_p (current_dir)))
1591 report_file_error ("Setting current directory",
1592 Fcons (current_buffer->directory, Qnil));
1593
1594 UNGCPRO;
1595 }
1596
1597 name = args[0];
1598 CHECK_STRING (name);
1599
1600 program = args[2];
1601
1602 if (!NILP (program))
1603 CHECK_STRING (program);
1604
1605 proc = make_process (name);
1606 /* If an error occurs and we can't start the process, we want to
1607 remove it from the process list. This means that each error
1608 check in create_process doesn't need to call remove_process
1609 itself; it's all taken care of here. */
1610 record_unwind_protect (start_process_unwind, proc);
1611
1612 XPROCESS (proc)->childp = Qt;
1613 XPROCESS (proc)->plist = Qnil;
1614 XPROCESS (proc)->type = Qreal;
1615 XPROCESS (proc)->buffer = buffer;
1616 XPROCESS (proc)->sentinel = Qnil;
1617 XPROCESS (proc)->filter = Qnil;
1618 XPROCESS (proc)->command = Flist (nargs - 2, args + 2);
1619
1620 #ifdef HAVE_GNUTLS
1621 /* AKA GNUTLS_INITSTAGE(proc). */
1622 XPROCESS (proc)->gnutls_initstage = GNUTLS_STAGE_EMPTY;
1623 XPROCESS (proc)->gnutls_cred_type = Qnil;
1624 #endif
1625
1626 #ifdef ADAPTIVE_READ_BUFFERING
1627 XPROCESS (proc)->adaptive_read_buffering
1628 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1629 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1630 #endif
1631
1632 /* Make the process marker point into the process buffer (if any). */
1633 if (BUFFERP (buffer))
1634 set_marker_both (XPROCESS (proc)->mark, buffer,
1635 BUF_ZV (XBUFFER (buffer)),
1636 BUF_ZV_BYTE (XBUFFER (buffer)));
1637
1638 {
1639 /* Decide coding systems for communicating with the process. Here
1640 we don't setup the structure coding_system nor pay attention to
1641 unibyte mode. They are done in create_process. */
1642
1643 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1644 Lisp_Object coding_systems = Qt;
1645 Lisp_Object val, *args2;
1646 struct gcpro gcpro1, gcpro2;
1647
1648 val = Vcoding_system_for_read;
1649 if (NILP (val))
1650 {
1651 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
1652 args2[0] = Qstart_process;
1653 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1654 GCPRO2 (proc, current_dir);
1655 if (!NILP (program))
1656 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1657 UNGCPRO;
1658 if (CONSP (coding_systems))
1659 val = XCAR (coding_systems);
1660 else if (CONSP (Vdefault_process_coding_system))
1661 val = XCAR (Vdefault_process_coding_system);
1662 }
1663 XPROCESS (proc)->decode_coding_system = val;
1664
1665 val = Vcoding_system_for_write;
1666 if (NILP (val))
1667 {
1668 if (EQ (coding_systems, Qt))
1669 {
1670 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof args2);
1671 args2[0] = Qstart_process;
1672 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1673 GCPRO2 (proc, current_dir);
1674 if (!NILP (program))
1675 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1676 UNGCPRO;
1677 }
1678 if (CONSP (coding_systems))
1679 val = XCDR (coding_systems);
1680 else if (CONSP (Vdefault_process_coding_system))
1681 val = XCDR (Vdefault_process_coding_system);
1682 }
1683 XPROCESS (proc)->encode_coding_system = val;
1684 }
1685
1686
1687 XPROCESS (proc)->decoding_buf = make_uninit_string (0);
1688 XPROCESS (proc)->decoding_carryover = 0;
1689 XPROCESS (proc)->encoding_buf = make_uninit_string (0);
1690
1691 XPROCESS (proc)->inherit_coding_system_flag
1692 = !(NILP (buffer) || !inherit_process_coding_system);
1693
1694 if (!NILP (program))
1695 {
1696 /* If program file name is not absolute, search our path for it.
1697 Put the name we will really use in TEM. */
1698 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1699 && !(SCHARS (program) > 1
1700 && IS_DEVICE_SEP (SREF (program, 1))))
1701 {
1702 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1703
1704 tem = Qnil;
1705 GCPRO4 (name, program, buffer, current_dir);
1706 openp (Vexec_path, program, Vexec_suffixes, &tem, make_number (X_OK));
1707 UNGCPRO;
1708 if (NILP (tem))
1709 report_file_error ("Searching for program", Fcons (program, Qnil));
1710 tem = Fexpand_file_name (tem, Qnil);
1711 }
1712 else
1713 {
1714 if (!NILP (Ffile_directory_p (program)))
1715 error ("Specified program for new process is a directory");
1716 tem = program;
1717 }
1718
1719 /* If program file name starts with /: for quoting a magic name,
1720 discard that. */
1721 if (SBYTES (tem) > 2 && SREF (tem, 0) == '/'
1722 && SREF (tem, 1) == ':')
1723 tem = Fsubstring (tem, make_number (2), Qnil);
1724
1725 {
1726 struct gcpro gcpro1;
1727 GCPRO1 (tem);
1728
1729 /* Encode the file name and put it in NEW_ARGV.
1730 That's where the child will use it to execute the program. */
1731 tem = Fcons (ENCODE_FILE (tem), Qnil);
1732
1733 /* Here we encode arguments by the coding system used for sending
1734 data to the process. We don't support using different coding
1735 systems for encoding arguments and for encoding data sent to the
1736 process. */
1737
1738 for (i = 3; i < nargs; i++)
1739 {
1740 tem = Fcons (args[i], tem);
1741 CHECK_STRING (XCAR (tem));
1742 if (STRING_MULTIBYTE (XCAR (tem)))
1743 XSETCAR (tem,
1744 code_convert_string_norecord
1745 (XCAR (tem), XPROCESS (proc)->encode_coding_system, 1));
1746 }
1747
1748 UNGCPRO;
1749 }
1750
1751 /* Now that everything is encoded we can collect the strings into
1752 NEW_ARGV. */
1753 new_argv = (unsigned char **) alloca ((nargs - 1) * sizeof (char *));
1754 new_argv[nargs - 2] = 0;
1755
1756 for (i = nargs - 3; i >= 0; i--)
1757 {
1758 new_argv[i] = SDATA (XCAR (tem));
1759 tem = XCDR (tem);
1760 }
1761
1762 create_process (proc, (char **) new_argv, current_dir);
1763 }
1764 else
1765 create_pty (proc);
1766
1767 return unbind_to (count, proc);
1768 }
1769
1770 /* This function is the unwind_protect form for Fstart_process. If
1771 PROC doesn't have its pid set, then we know someone has signaled
1772 an error and the process wasn't started successfully, so we should
1773 remove it from the process list. */
1774 static Lisp_Object
1775 start_process_unwind (Lisp_Object proc)
1776 {
1777 if (!PROCESSP (proc))
1778 abort ();
1779
1780 /* Was PROC started successfully? */
1781 if (XPROCESS (proc)->pid == -1)
1782 remove_process (proc);
1783
1784 return Qnil;
1785 }
1786
1787 static void
1788 create_process_1 (struct atimer *timer)
1789 {
1790 /* Nothing to do. */
1791 }
1792
1793
1794 void
1795 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1796 {
1797 int inchannel, outchannel;
1798 pid_t pid;
1799 int sv[2];
1800 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1801 int wait_child_setup[2];
1802 #endif
1803 sigset_t procmask;
1804 sigset_t blocked;
1805 struct sigaction sigint_action;
1806 struct sigaction sigquit_action;
1807 #ifdef AIX
1808 struct sigaction sighup_action;
1809 #endif
1810 /* Use volatile to protect variables from being clobbered by longjmp. */
1811 volatile int forkin, forkout;
1812 volatile int pty_flag = 0;
1813 #ifndef USE_CRT_DLL
1814 extern char **environ;
1815 #endif
1816
1817 inchannel = outchannel = -1;
1818
1819 #ifdef HAVE_PTYS
1820 if (!NILP (Vprocess_connection_type))
1821 outchannel = inchannel = allocate_pty ();
1822
1823 if (inchannel >= 0)
1824 {
1825 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1826 /* On most USG systems it does not work to open the pty's tty here,
1827 then close it and reopen it in the child. */
1828 #ifdef O_NOCTTY
1829 /* Don't let this terminal become our controlling terminal
1830 (in case we don't have one). */
1831 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1832 #else
1833 forkout = forkin = emacs_open (pty_name, O_RDWR, 0);
1834 #endif
1835 if (forkin < 0)
1836 report_file_error ("Opening pty", Qnil);
1837 #else
1838 forkin = forkout = -1;
1839 #endif /* not USG, or USG_SUBTTY_WORKS */
1840 pty_flag = 1;
1841 }
1842 else
1843 #endif /* HAVE_PTYS */
1844 {
1845 int tem;
1846 tem = pipe (sv);
1847 if (tem < 0)
1848 report_file_error ("Creating pipe", Qnil);
1849 inchannel = sv[0];
1850 forkout = sv[1];
1851 tem = pipe (sv);
1852 if (tem < 0)
1853 {
1854 emacs_close (inchannel);
1855 emacs_close (forkout);
1856 report_file_error ("Creating pipe", Qnil);
1857 }
1858 outchannel = sv[1];
1859 forkin = sv[0];
1860 }
1861
1862 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1863 {
1864 int tem;
1865
1866 tem = pipe (wait_child_setup);
1867 if (tem < 0)
1868 report_file_error ("Creating pipe", Qnil);
1869 tem = fcntl (wait_child_setup[1], F_GETFD, 0);
1870 if (tem >= 0)
1871 tem = fcntl (wait_child_setup[1], F_SETFD, tem | FD_CLOEXEC);
1872 if (tem < 0)
1873 {
1874 emacs_close (wait_child_setup[0]);
1875 emacs_close (wait_child_setup[1]);
1876 report_file_error ("Setting file descriptor flags", Qnil);
1877 }
1878 }
1879 #endif
1880
1881 #if 0
1882 /* Replaced by close_process_descs */
1883 set_exclusive_use (inchannel);
1884 set_exclusive_use (outchannel);
1885 #endif
1886
1887 #ifdef O_NONBLOCK
1888 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1889 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1890 #else
1891 #ifdef O_NDELAY
1892 fcntl (inchannel, F_SETFL, O_NDELAY);
1893 fcntl (outchannel, F_SETFL, O_NDELAY);
1894 #endif
1895 #endif
1896
1897 /* Record this as an active process, with its channels.
1898 As a result, child_setup will close Emacs's side of the pipes. */
1899 chan_process[inchannel] = process;
1900 XPROCESS (process)->infd = inchannel;
1901 XPROCESS (process)->outfd = outchannel;
1902
1903 /* Previously we recorded the tty descriptor used in the subprocess.
1904 It was only used for getting the foreground tty process, so now
1905 we just reopen the device (see emacs_get_tty_pgrp) as this is
1906 more portable (see USG_SUBTTY_WORKS above). */
1907
1908 XPROCESS (process)->pty_flag = pty_flag;
1909 XPROCESS (process)->status = Qrun;
1910 setup_process_coding_systems (process);
1911
1912 /* Delay interrupts until we have a chance to store
1913 the new fork's pid in its process structure */
1914 sigemptyset (&blocked);
1915 #ifdef SIGCHLD
1916 sigaddset (&blocked, SIGCHLD);
1917 #endif
1918 #ifdef HAVE_WORKING_VFORK
1919 /* On many hosts (e.g. Solaris 2.4), if a vforked child calls `signal',
1920 this sets the parent's signal handlers as well as the child's.
1921 So delay all interrupts whose handlers the child might munge,
1922 and record the current handlers so they can be restored later. */
1923 sigaddset (&blocked, SIGINT ); sigaction (SIGINT , 0, &sigint_action );
1924 sigaddset (&blocked, SIGQUIT); sigaction (SIGQUIT, 0, &sigquit_action);
1925 #ifdef AIX
1926 sigaddset (&blocked, SIGHUP ); sigaction (SIGHUP , 0, &sighup_action );
1927 #endif
1928 #endif /* HAVE_WORKING_VFORK */
1929 sigprocmask (SIG_BLOCK, &blocked, &procmask);
1930
1931 FD_SET (inchannel, &input_wait_mask);
1932 FD_SET (inchannel, &non_keyboard_wait_mask);
1933 if (inchannel > max_process_desc)
1934 max_process_desc = inchannel;
1935
1936 /* Until we store the proper pid, enable sigchld_handler
1937 to recognize an unknown pid as standing for this process.
1938 It is very important not to let this `marker' value stay
1939 in the table after this function has returned; if it does
1940 it might cause call-process to hang and subsequent asynchronous
1941 processes to get their return values scrambled. */
1942 XPROCESS (process)->pid = -1;
1943
1944 BLOCK_INPUT;
1945
1946 {
1947 /* child_setup must clobber environ on systems with true vfork.
1948 Protect it from permanent change. */
1949 char **save_environ = environ;
1950
1951 current_dir = ENCODE_FILE (current_dir);
1952
1953 #ifndef WINDOWSNT
1954 pid = vfork ();
1955 if (pid == 0)
1956 #endif /* not WINDOWSNT */
1957 {
1958 int xforkin = forkin;
1959 int xforkout = forkout;
1960
1961 #if 0 /* This was probably a mistake--it duplicates code later on,
1962 but fails to handle all the cases. */
1963 /* Make sure SIGCHLD is not blocked in the child. */
1964 sigsetmask (SIGEMPTYMASK);
1965 #endif
1966
1967 /* Make the pty be the controlling terminal of the process. */
1968 #ifdef HAVE_PTYS
1969 /* First, disconnect its current controlling terminal. */
1970 #ifdef HAVE_SETSID
1971 /* We tried doing setsid only if pty_flag, but it caused
1972 process_set_signal to fail on SGI when using a pipe. */
1973 setsid ();
1974 /* Make the pty's terminal the controlling terminal. */
1975 if (pty_flag && xforkin >= 0)
1976 {
1977 #ifdef TIOCSCTTY
1978 /* We ignore the return value
1979 because faith@cs.unc.edu says that is necessary on Linux. */
1980 ioctl (xforkin, TIOCSCTTY, 0);
1981 #endif
1982 }
1983 #else /* not HAVE_SETSID */
1984 #ifdef USG
1985 /* It's very important to call setpgrp here and no time
1986 afterwards. Otherwise, we lose our controlling tty which
1987 is set when we open the pty. */
1988 setpgrp ();
1989 #endif /* USG */
1990 #endif /* not HAVE_SETSID */
1991 #if defined (LDISC1)
1992 if (pty_flag && xforkin >= 0)
1993 {
1994 struct termios t;
1995 tcgetattr (xforkin, &t);
1996 t.c_lflag = LDISC1;
1997 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
1998 emacs_write (1, "create_process/tcsetattr LDISC1 failed\n", 39);
1999 }
2000 #else
2001 #if defined (NTTYDISC) && defined (TIOCSETD)
2002 if (pty_flag && xforkin >= 0)
2003 {
2004 /* Use new line discipline. */
2005 int ldisc = NTTYDISC;
2006 ioctl (xforkin, TIOCSETD, &ldisc);
2007 }
2008 #endif
2009 #endif
2010 #ifdef TIOCNOTTY
2011 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
2012 can do TIOCSPGRP only to the process's controlling tty. */
2013 if (pty_flag)
2014 {
2015 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
2016 I can't test it since I don't have 4.3. */
2017 int j = emacs_open ("/dev/tty", O_RDWR, 0);
2018 if (j >= 0)
2019 {
2020 ioctl (j, TIOCNOTTY, 0);
2021 emacs_close (j);
2022 }
2023 #ifndef USG
2024 /* In order to get a controlling terminal on some versions
2025 of BSD, it is necessary to put the process in pgrp 0
2026 before it opens the terminal. */
2027 #ifdef HAVE_SETPGID
2028 setpgid (0, 0);
2029 #else
2030 setpgrp (0, 0);
2031 #endif
2032 #endif
2033 }
2034 #endif /* TIOCNOTTY */
2035
2036 #if !defined (DONT_REOPEN_PTY)
2037 /*** There is a suggestion that this ought to be a
2038 conditional on TIOCSPGRP,
2039 or !(defined (HAVE_SETSID) && defined (TIOCSCTTY)).
2040 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
2041 that system does seem to need this code, even though
2042 both HAVE_SETSID and TIOCSCTTY are defined. */
2043 /* Now close the pty (if we had it open) and reopen it.
2044 This makes the pty the controlling terminal of the subprocess. */
2045 if (pty_flag)
2046 {
2047
2048 /* I wonder if emacs_close (emacs_open (pty_name, ...))
2049 would work? */
2050 if (xforkin >= 0)
2051 emacs_close (xforkin);
2052 xforkout = xforkin = emacs_open (pty_name, O_RDWR, 0);
2053
2054 if (xforkin < 0)
2055 {
2056 emacs_write (1, "Couldn't open the pty terminal ", 31);
2057 emacs_write (1, pty_name, strlen (pty_name));
2058 emacs_write (1, "\n", 1);
2059 _exit (1);
2060 }
2061
2062 }
2063 #endif /* not DONT_REOPEN_PTY */
2064
2065 #ifdef SETUP_SLAVE_PTY
2066 if (pty_flag)
2067 {
2068 SETUP_SLAVE_PTY;
2069 }
2070 #endif /* SETUP_SLAVE_PTY */
2071 #ifdef AIX
2072 /* On AIX, we've disabled SIGHUP above once we start a child on a pty.
2073 Now reenable it in the child, so it will die when we want it to. */
2074 if (pty_flag)
2075 signal (SIGHUP, SIG_DFL);
2076 #endif
2077 #endif /* HAVE_PTYS */
2078
2079 signal (SIGINT, SIG_DFL);
2080 signal (SIGQUIT, SIG_DFL);
2081
2082 /* Stop blocking signals in the child. */
2083 sigprocmask (SIG_SETMASK, &procmask, 0);
2084
2085 if (pty_flag)
2086 child_setup_tty (xforkout);
2087 #ifdef WINDOWSNT
2088 pid = child_setup (xforkin, xforkout, xforkout,
2089 new_argv, 1, current_dir);
2090 #else /* not WINDOWSNT */
2091 #ifdef FD_CLOEXEC
2092 emacs_close (wait_child_setup[0]);
2093 #endif
2094 child_setup (xforkin, xforkout, xforkout,
2095 new_argv, 1, current_dir);
2096 #endif /* not WINDOWSNT */
2097 }
2098 environ = save_environ;
2099 }
2100
2101 UNBLOCK_INPUT;
2102
2103 /* This runs in the Emacs process. */
2104 if (pid < 0)
2105 {
2106 if (forkin >= 0)
2107 emacs_close (forkin);
2108 if (forkin != forkout && forkout >= 0)
2109 emacs_close (forkout);
2110 }
2111 else
2112 {
2113 /* vfork succeeded. */
2114 XPROCESS (process)->pid = pid;
2115
2116 #ifdef WINDOWSNT
2117 register_child (pid, inchannel);
2118 #endif /* WINDOWSNT */
2119
2120 /* If the subfork execv fails, and it exits,
2121 this close hangs. I don't know why.
2122 So have an interrupt jar it loose. */
2123 {
2124 struct atimer *timer;
2125 EMACS_TIME offset;
2126
2127 stop_polling ();
2128 EMACS_SET_SECS_USECS (offset, 1, 0);
2129 timer = start_atimer (ATIMER_RELATIVE, offset, create_process_1, 0);
2130
2131 if (forkin >= 0)
2132 emacs_close (forkin);
2133
2134 cancel_atimer (timer);
2135 start_polling ();
2136 }
2137
2138 if (forkin != forkout && forkout >= 0)
2139 emacs_close (forkout);
2140
2141 #ifdef HAVE_PTYS
2142 if (pty_flag)
2143 XPROCESS (process)->tty_name = build_string (pty_name);
2144 else
2145 #endif
2146 XPROCESS (process)->tty_name = Qnil;
2147
2148 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
2149 /* Wait for child_setup to complete in case that vfork is
2150 actually defined as fork. The descriptor wait_child_setup[1]
2151 of a pipe is closed at the child side either by close-on-exec
2152 on successful execvp or the _exit call in child_setup. */
2153 {
2154 char dummy;
2155
2156 emacs_close (wait_child_setup[1]);
2157 emacs_read (wait_child_setup[0], &dummy, 1);
2158 emacs_close (wait_child_setup[0]);
2159 }
2160 #endif
2161 }
2162
2163 /* Restore the signal state whether vfork succeeded or not.
2164 (We will signal an error, below, if it failed.) */
2165 #ifdef HAVE_WORKING_VFORK
2166 /* Restore the parent's signal handlers. */
2167 sigaction (SIGINT, &sigint_action, 0);
2168 sigaction (SIGQUIT, &sigquit_action, 0);
2169 #ifdef AIX
2170 sigaction (SIGHUP, &sighup_action, 0);
2171 #endif
2172 #endif /* HAVE_WORKING_VFORK */
2173 /* Stop blocking signals in the parent. */
2174 sigprocmask (SIG_SETMASK, &procmask, 0);
2175
2176 /* Now generate the error if vfork failed. */
2177 if (pid < 0)
2178 report_file_error ("Doing vfork", Qnil);
2179 }
2180
2181 void
2182 create_pty (Lisp_Object process)
2183 {
2184 int inchannel, outchannel;
2185
2186 /* Use volatile to protect variables from being clobbered by longjmp. */
2187 volatile int forkin, forkout;
2188 volatile int pty_flag = 0;
2189
2190 inchannel = outchannel = -1;
2191
2192 #ifdef HAVE_PTYS
2193 if (!NILP (Vprocess_connection_type))
2194 outchannel = inchannel = allocate_pty ();
2195
2196 if (inchannel >= 0)
2197 {
2198 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2199 /* On most USG systems it does not work to open the pty's tty here,
2200 then close it and reopen it in the child. */
2201 #ifdef O_NOCTTY
2202 /* Don't let this terminal become our controlling terminal
2203 (in case we don't have one). */
2204 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
2205 #else
2206 forkout = forkin = emacs_open (pty_name, O_RDWR, 0);
2207 #endif
2208 if (forkin < 0)
2209 report_file_error ("Opening pty", Qnil);
2210 #if defined (DONT_REOPEN_PTY)
2211 /* In the case that vfork is defined as fork, the parent process
2212 (Emacs) may send some data before the child process completes
2213 tty options setup. So we setup tty before forking. */
2214 child_setup_tty (forkout);
2215 #endif /* DONT_REOPEN_PTY */
2216 #else
2217 forkin = forkout = -1;
2218 #endif /* not USG, or USG_SUBTTY_WORKS */
2219 pty_flag = 1;
2220 }
2221 #endif /* HAVE_PTYS */
2222
2223 #ifdef O_NONBLOCK
2224 fcntl (inchannel, F_SETFL, O_NONBLOCK);
2225 fcntl (outchannel, F_SETFL, O_NONBLOCK);
2226 #else
2227 #ifdef O_NDELAY
2228 fcntl (inchannel, F_SETFL, O_NDELAY);
2229 fcntl (outchannel, F_SETFL, O_NDELAY);
2230 #endif
2231 #endif
2232
2233 /* Record this as an active process, with its channels.
2234 As a result, child_setup will close Emacs's side of the pipes. */
2235 chan_process[inchannel] = process;
2236 XPROCESS (process)->infd = inchannel;
2237 XPROCESS (process)->outfd = outchannel;
2238
2239 /* Previously we recorded the tty descriptor used in the subprocess.
2240 It was only used for getting the foreground tty process, so now
2241 we just reopen the device (see emacs_get_tty_pgrp) as this is
2242 more portable (see USG_SUBTTY_WORKS above). */
2243
2244 XPROCESS (process)->pty_flag = pty_flag;
2245 XPROCESS (process)->status = Qrun;
2246 setup_process_coding_systems (process);
2247
2248 FD_SET (inchannel, &input_wait_mask);
2249 FD_SET (inchannel, &non_keyboard_wait_mask);
2250 if (inchannel > max_process_desc)
2251 max_process_desc = inchannel;
2252
2253 XPROCESS (process)->pid = -2;
2254 #ifdef HAVE_PTYS
2255 if (pty_flag)
2256 XPROCESS (process)->tty_name = build_string (pty_name);
2257 else
2258 #endif
2259 XPROCESS (process)->tty_name = Qnil;
2260 }
2261
2262 \f
2263 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2264 The address family of sa is not included in the result. */
2265
2266 static Lisp_Object
2267 conv_sockaddr_to_lisp (struct sockaddr *sa, int len)
2268 {
2269 Lisp_Object address;
2270 int i;
2271 unsigned char *cp;
2272 register struct Lisp_Vector *p;
2273
2274 /* Workaround for a bug in getsockname on BSD: Names bound to
2275 sockets in the UNIX domain are inaccessible; getsockname returns
2276 a zero length name. */
2277 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
2278 return empty_unibyte_string;
2279
2280 switch (sa->sa_family)
2281 {
2282 case AF_INET:
2283 {
2284 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2285 len = sizeof (sin->sin_addr) + 1;
2286 address = Fmake_vector (make_number (len), Qnil);
2287 p = XVECTOR (address);
2288 p->contents[--len] = make_number (ntohs (sin->sin_port));
2289 cp = (unsigned char *) &sin->sin_addr;
2290 break;
2291 }
2292 #ifdef AF_INET6
2293 case AF_INET6:
2294 {
2295 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2296 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
2297 len = sizeof (sin6->sin6_addr)/2 + 1;
2298 address = Fmake_vector (make_number (len), Qnil);
2299 p = XVECTOR (address);
2300 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2301 for (i = 0; i < len; i++)
2302 p->contents[i] = make_number (ntohs (ip6[i]));
2303 return address;
2304 }
2305 #endif
2306 #ifdef HAVE_LOCAL_SOCKETS
2307 case AF_LOCAL:
2308 {
2309 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2310 for (i = 0; i < sizeof (sockun->sun_path); i++)
2311 if (sockun->sun_path[i] == 0)
2312 break;
2313 return make_unibyte_string (sockun->sun_path, i);
2314 }
2315 #endif
2316 default:
2317 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2318 address = Fcons (make_number (sa->sa_family),
2319 Fmake_vector (make_number (len), Qnil));
2320 p = XVECTOR (XCDR (address));
2321 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2322 break;
2323 }
2324
2325 i = 0;
2326 while (i < len)
2327 p->contents[i++] = make_number (*cp++);
2328
2329 return address;
2330 }
2331
2332
2333 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2334
2335 static int
2336 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2337 {
2338 register struct Lisp_Vector *p;
2339
2340 if (VECTORP (address))
2341 {
2342 p = XVECTOR (address);
2343 if (p->size == 5)
2344 {
2345 *familyp = AF_INET;
2346 return sizeof (struct sockaddr_in);
2347 }
2348 #ifdef AF_INET6
2349 else if (p->size == 9)
2350 {
2351 *familyp = AF_INET6;
2352 return sizeof (struct sockaddr_in6);
2353 }
2354 #endif
2355 }
2356 #ifdef HAVE_LOCAL_SOCKETS
2357 else if (STRINGP (address))
2358 {
2359 *familyp = AF_LOCAL;
2360 return sizeof (struct sockaddr_un);
2361 }
2362 #endif
2363 else if (CONSP (address) && INTEGERP (XCAR (address)) && VECTORP (XCDR (address)))
2364 {
2365 struct sockaddr *sa;
2366 *familyp = XINT (XCAR (address));
2367 p = XVECTOR (XCDR (address));
2368 return p->size + sizeof (sa->sa_family);
2369 }
2370 return 0;
2371 }
2372
2373 /* Convert an address object (vector or string) to an internal sockaddr.
2374
2375 The address format has been basically validated by
2376 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2377 it could have come from user data. So if FAMILY is not valid,
2378 we return after zeroing *SA. */
2379
2380 static void
2381 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2382 {
2383 register struct Lisp_Vector *p;
2384 register unsigned char *cp = NULL;
2385 register int i;
2386
2387 memset (sa, 0, len);
2388
2389 if (VECTORP (address))
2390 {
2391 p = XVECTOR (address);
2392 if (family == AF_INET)
2393 {
2394 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2395 len = sizeof (sin->sin_addr) + 1;
2396 i = XINT (p->contents[--len]);
2397 sin->sin_port = htons (i);
2398 cp = (unsigned char *)&sin->sin_addr;
2399 sa->sa_family = family;
2400 }
2401 #ifdef AF_INET6
2402 else if (family == AF_INET6)
2403 {
2404 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2405 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2406 len = sizeof (sin6->sin6_addr) + 1;
2407 i = XINT (p->contents[--len]);
2408 sin6->sin6_port = htons (i);
2409 for (i = 0; i < len; i++)
2410 if (INTEGERP (p->contents[i]))
2411 {
2412 int j = XFASTINT (p->contents[i]) & 0xffff;
2413 ip6[i] = ntohs (j);
2414 }
2415 sa->sa_family = family;
2416 return;
2417 }
2418 #endif
2419 else
2420 return;
2421 }
2422 else if (STRINGP (address))
2423 {
2424 #ifdef HAVE_LOCAL_SOCKETS
2425 if (family == AF_LOCAL)
2426 {
2427 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2428 cp = SDATA (address);
2429 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2430 sockun->sun_path[i] = *cp++;
2431 sa->sa_family = family;
2432 }
2433 #endif
2434 return;
2435 }
2436 else
2437 {
2438 p = XVECTOR (XCDR (address));
2439 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2440 }
2441
2442 for (i = 0; i < len; i++)
2443 if (INTEGERP (p->contents[i]))
2444 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2445 }
2446
2447 #ifdef DATAGRAM_SOCKETS
2448 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2449 1, 1, 0,
2450 doc: /* Get the current datagram address associated with PROCESS. */)
2451 (Lisp_Object process)
2452 {
2453 int channel;
2454
2455 CHECK_PROCESS (process);
2456
2457 if (!DATAGRAM_CONN_P (process))
2458 return Qnil;
2459
2460 channel = XPROCESS (process)->infd;
2461 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2462 datagram_address[channel].len);
2463 }
2464
2465 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2466 2, 2, 0,
2467 doc: /* Set the datagram address for PROCESS to ADDRESS.
2468 Returns nil upon error setting address, ADDRESS otherwise. */)
2469 (Lisp_Object process, Lisp_Object address)
2470 {
2471 int channel;
2472 int family, len;
2473
2474 CHECK_PROCESS (process);
2475
2476 if (!DATAGRAM_CONN_P (process))
2477 return Qnil;
2478
2479 channel = XPROCESS (process)->infd;
2480
2481 len = get_lisp_to_sockaddr_size (address, &family);
2482 if (datagram_address[channel].len != len)
2483 return Qnil;
2484 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2485 return address;
2486 }
2487 #endif
2488 \f
2489
2490 static const struct socket_options {
2491 /* The name of this option. Should be lowercase version of option
2492 name without SO_ prefix. */
2493 const char *name;
2494 /* Option level SOL_... */
2495 int optlevel;
2496 /* Option number SO_... */
2497 int optnum;
2498 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2499 enum { OPIX_NONE=0, OPIX_MISC=1, OPIX_REUSEADDR=2 } optbit;
2500 } socket_options[] =
2501 {
2502 #ifdef SO_BINDTODEVICE
2503 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2504 #endif
2505 #ifdef SO_BROADCAST
2506 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2507 #endif
2508 #ifdef SO_DONTROUTE
2509 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2510 #endif
2511 #ifdef SO_KEEPALIVE
2512 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2513 #endif
2514 #ifdef SO_LINGER
2515 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2516 #endif
2517 #ifdef SO_OOBINLINE
2518 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2519 #endif
2520 #ifdef SO_PRIORITY
2521 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2522 #endif
2523 #ifdef SO_REUSEADDR
2524 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2525 #endif
2526 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2527 };
2528
2529 /* Set option OPT to value VAL on socket S.
2530
2531 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2532 Signals an error if setting a known option fails.
2533 */
2534
2535 static int
2536 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2537 {
2538 char *name;
2539 const struct socket_options *sopt;
2540 int ret = 0;
2541
2542 CHECK_SYMBOL (opt);
2543
2544 name = (char *) SDATA (SYMBOL_NAME (opt));
2545 for (sopt = socket_options; sopt->name; sopt++)
2546 if (strcmp (name, sopt->name) == 0)
2547 break;
2548
2549 switch (sopt->opttype)
2550 {
2551 case SOPT_BOOL:
2552 {
2553 int optval;
2554 optval = NILP (val) ? 0 : 1;
2555 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2556 &optval, sizeof (optval));
2557 break;
2558 }
2559
2560 case SOPT_INT:
2561 {
2562 int optval;
2563 if (INTEGERP (val))
2564 optval = XINT (val);
2565 else
2566 error ("Bad option value for %s", name);
2567 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2568 &optval, sizeof (optval));
2569 break;
2570 }
2571
2572 #ifdef SO_BINDTODEVICE
2573 case SOPT_IFNAME:
2574 {
2575 char devname[IFNAMSIZ+1];
2576
2577 /* This is broken, at least in the Linux 2.4 kernel.
2578 To unbind, the arg must be a zero integer, not the empty string.
2579 This should work on all systems. KFS. 2003-09-23. */
2580 memset (devname, 0, sizeof devname);
2581 if (STRINGP (val))
2582 {
2583 char *arg = (char *) SDATA (val);
2584 int len = min (strlen (arg), IFNAMSIZ);
2585 memcpy (devname, arg, len);
2586 }
2587 else if (!NILP (val))
2588 error ("Bad option value for %s", name);
2589 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2590 devname, IFNAMSIZ);
2591 break;
2592 }
2593 #endif
2594
2595 #ifdef SO_LINGER
2596 case SOPT_LINGER:
2597 {
2598 struct linger linger;
2599
2600 linger.l_onoff = 1;
2601 linger.l_linger = 0;
2602 if (INTEGERP (val))
2603 linger.l_linger = XINT (val);
2604 else
2605 linger.l_onoff = NILP (val) ? 0 : 1;
2606 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2607 &linger, sizeof (linger));
2608 break;
2609 }
2610 #endif
2611
2612 default:
2613 return 0;
2614 }
2615
2616 if (ret < 0)
2617 report_file_error ("Cannot set network option",
2618 Fcons (opt, Fcons (val, Qnil)));
2619 return (1 << sopt->optbit);
2620 }
2621
2622
2623 DEFUN ("set-network-process-option",
2624 Fset_network_process_option, Sset_network_process_option,
2625 3, 4, 0,
2626 doc: /* For network process PROCESS set option OPTION to value VALUE.
2627 See `make-network-process' for a list of options and values.
2628 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2629 OPTION is not a supported option, return nil instead; otherwise return t. */)
2630 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2631 {
2632 int s;
2633 struct Lisp_Process *p;
2634
2635 CHECK_PROCESS (process);
2636 p = XPROCESS (process);
2637 if (!NETCONN1_P (p))
2638 error ("Process is not a network process");
2639
2640 s = p->infd;
2641 if (s < 0)
2642 error ("Process is not running");
2643
2644 if (set_socket_option (s, option, value))
2645 {
2646 p->childp = Fplist_put (p->childp, option, value);
2647 return Qt;
2648 }
2649
2650 if (NILP (no_error))
2651 error ("Unknown or unsupported option");
2652
2653 return Qnil;
2654 }
2655
2656 \f
2657 DEFUN ("serial-process-configure",
2658 Fserial_process_configure,
2659 Sserial_process_configure,
2660 0, MANY, 0,
2661 doc: /* Configure speed, bytesize, etc. of a serial process.
2662
2663 Arguments are specified as keyword/argument pairs. Attributes that
2664 are not given are re-initialized from the process's current
2665 configuration (available via the function `process-contact') or set to
2666 reasonable default values. The following arguments are defined:
2667
2668 :process PROCESS
2669 :name NAME
2670 :buffer BUFFER
2671 :port PORT
2672 -- Any of these arguments can be given to identify the process that is
2673 to be configured. If none of these arguments is given, the current
2674 buffer's process is used.
2675
2676 :speed SPEED -- SPEED is the speed of the serial port in bits per
2677 second, also called baud rate. Any value can be given for SPEED, but
2678 most serial ports work only at a few defined values between 1200 and
2679 115200, with 9600 being the most common value. If SPEED is nil, the
2680 serial port is not configured any further, i.e., all other arguments
2681 are ignored. This may be useful for special serial ports such as
2682 Bluetooth-to-serial converters which can only be configured through AT
2683 commands. A value of nil for SPEED can be used only when passed
2684 through `make-serial-process' or `serial-term'.
2685
2686 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2687 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2688
2689 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2690 `odd' (use odd parity), or the symbol `even' (use even parity). If
2691 PARITY is not given, no parity is used.
2692
2693 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2694 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2695 is not given or nil, 1 stopbit is used.
2696
2697 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2698 flowcontrol to be used, which is either nil (don't use flowcontrol),
2699 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2700 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2701 flowcontrol is used.
2702
2703 `serial-process-configure' is called by `make-serial-process' for the
2704 initial configuration of the serial port.
2705
2706 Examples:
2707
2708 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2709
2710 \(serial-process-configure
2711 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2712
2713 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2714
2715 usage: (serial-process-configure &rest ARGS) */)
2716 (int nargs, Lisp_Object *args)
2717 {
2718 struct Lisp_Process *p;
2719 Lisp_Object contact = Qnil;
2720 Lisp_Object proc = Qnil;
2721 struct gcpro gcpro1;
2722
2723 contact = Flist (nargs, args);
2724 GCPRO1 (contact);
2725
2726 proc = Fplist_get (contact, QCprocess);
2727 if (NILP (proc))
2728 proc = Fplist_get (contact, QCname);
2729 if (NILP (proc))
2730 proc = Fplist_get (contact, QCbuffer);
2731 if (NILP (proc))
2732 proc = Fplist_get (contact, QCport);
2733 proc = get_process (proc);
2734 p = XPROCESS (proc);
2735 if (!EQ (p->type, Qserial))
2736 error ("Not a serial process");
2737
2738 if (NILP (Fplist_get (p->childp, QCspeed)))
2739 {
2740 UNGCPRO;
2741 return Qnil;
2742 }
2743
2744 serial_configure (p, contact);
2745
2746 UNGCPRO;
2747 return Qnil;
2748 }
2749
2750 /* Used by make-serial-process to recover from errors. */
2751 Lisp_Object make_serial_process_unwind (Lisp_Object proc)
2752 {
2753 if (!PROCESSP (proc))
2754 abort ();
2755 remove_process (proc);
2756 return Qnil;
2757 }
2758
2759 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2760 0, MANY, 0,
2761 doc: /* Create and return a serial port process.
2762
2763 In Emacs, serial port connections are represented by process objects,
2764 so input and output work as for subprocesses, and `delete-process'
2765 closes a serial port connection. However, a serial process has no
2766 process id, it cannot be signaled, and the status codes are different
2767 from normal processes.
2768
2769 `make-serial-process' creates a process and a buffer, on which you
2770 probably want to use `process-send-string'. Try \\[serial-term] for
2771 an interactive terminal. See below for examples.
2772
2773 Arguments are specified as keyword/argument pairs. The following
2774 arguments are defined:
2775
2776 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2777 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2778 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2779 the backslashes in strings).
2780
2781 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2782 which is called by `make-serial-process'.
2783
2784 :name NAME -- NAME is the name of the process. If NAME is not given,
2785 the value of PORT is used.
2786
2787 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2788 with the process. Process output goes at the end of that buffer,
2789 unless you specify an output stream or filter function to handle the
2790 output. If BUFFER is not given, the value of NAME is used.
2791
2792 :coding CODING -- If CODING is a symbol, it specifies the coding
2793 system used for both reading and writing for this process. If CODING
2794 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2795 ENCODING is used for writing.
2796
2797 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2798 the process is running. If BOOL is not given, query before exiting.
2799
2800 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2801 In the stopped state, a serial process does not accept incoming data,
2802 but you can send outgoing data. The stopped state is cleared by
2803 `continue-process' and set by `stop-process'.
2804
2805 :filter FILTER -- Install FILTER as the process filter.
2806
2807 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2808
2809 :plist PLIST -- Install PLIST as the initial plist of the process.
2810
2811 :speed
2812 :bytesize
2813 :parity
2814 :stopbits
2815 :flowcontrol
2816 -- These arguments are handled by `serial-process-configure', which is
2817 called by `make-serial-process'.
2818
2819 The original argument list, possibly modified by later configuration,
2820 is available via the function `process-contact'.
2821
2822 Examples:
2823
2824 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2825
2826 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2827
2828 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2829
2830 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2831
2832 usage: (make-serial-process &rest ARGS) */)
2833 (int nargs, Lisp_Object *args)
2834 {
2835 int fd = -1;
2836 Lisp_Object proc, contact, port;
2837 struct Lisp_Process *p;
2838 struct gcpro gcpro1;
2839 Lisp_Object name, buffer;
2840 Lisp_Object tem, val;
2841 int specpdl_count = -1;
2842
2843 if (nargs == 0)
2844 return Qnil;
2845
2846 contact = Flist (nargs, args);
2847 GCPRO1 (contact);
2848
2849 port = Fplist_get (contact, QCport);
2850 if (NILP (port))
2851 error ("No port specified");
2852 CHECK_STRING (port);
2853
2854 if (NILP (Fplist_member (contact, QCspeed)))
2855 error (":speed not specified");
2856 if (!NILP (Fplist_get (contact, QCspeed)))
2857 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2858
2859 name = Fplist_get (contact, QCname);
2860 if (NILP (name))
2861 name = port;
2862 CHECK_STRING (name);
2863 proc = make_process (name);
2864 specpdl_count = SPECPDL_INDEX ();
2865 record_unwind_protect (make_serial_process_unwind, proc);
2866 p = XPROCESS (proc);
2867
2868 fd = serial_open ((char*) SDATA (port));
2869 p->infd = fd;
2870 p->outfd = fd;
2871 if (fd > max_process_desc)
2872 max_process_desc = fd;
2873 chan_process[fd] = proc;
2874
2875 buffer = Fplist_get (contact, QCbuffer);
2876 if (NILP (buffer))
2877 buffer = name;
2878 buffer = Fget_buffer_create (buffer);
2879 p->buffer = buffer;
2880
2881 p->childp = contact;
2882 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
2883 p->type = Qserial;
2884 p->sentinel = Fplist_get (contact, QCsentinel);
2885 p->filter = Fplist_get (contact, QCfilter);
2886 p->log = Qnil;
2887 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2888 p->kill_without_query = 1;
2889 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2890 p->command = Qt;
2891 p->pty_flag = 0;
2892
2893 if (!EQ (p->command, Qt))
2894 {
2895 FD_SET (fd, &input_wait_mask);
2896 FD_SET (fd, &non_keyboard_wait_mask);
2897 }
2898
2899 if (BUFFERP (buffer))
2900 {
2901 set_marker_both (p->mark, buffer,
2902 BUF_ZV (XBUFFER (buffer)),
2903 BUF_ZV_BYTE (XBUFFER (buffer)));
2904 }
2905
2906 tem = Fplist_member (contact, QCcoding);
2907 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2908 tem = Qnil;
2909
2910 val = Qnil;
2911 if (!NILP (tem))
2912 {
2913 val = XCAR (XCDR (tem));
2914 if (CONSP (val))
2915 val = XCAR (val);
2916 }
2917 else if (!NILP (Vcoding_system_for_read))
2918 val = Vcoding_system_for_read;
2919 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
2920 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
2921 val = Qnil;
2922 p->decode_coding_system = val;
2923
2924 val = Qnil;
2925 if (!NILP (tem))
2926 {
2927 val = XCAR (XCDR (tem));
2928 if (CONSP (val))
2929 val = XCDR (val);
2930 }
2931 else if (!NILP (Vcoding_system_for_write))
2932 val = Vcoding_system_for_write;
2933 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
2934 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
2935 val = Qnil;
2936 p->encode_coding_system = val;
2937
2938 setup_process_coding_systems (proc);
2939 p->decoding_buf = make_uninit_string (0);
2940 p->decoding_carryover = 0;
2941 p->encoding_buf = make_uninit_string (0);
2942 p->inherit_coding_system_flag
2943 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2944
2945 Fserial_process_configure (nargs, args);
2946
2947 specpdl_ptr = specpdl + specpdl_count;
2948
2949 UNGCPRO;
2950 return proc;
2951 }
2952
2953 /* Create a network stream/datagram client/server process. Treated
2954 exactly like a normal process when reading and writing. Primary
2955 differences are in status display and process deletion. A network
2956 connection has no PID; you cannot signal it. All you can do is
2957 stop/continue it and deactivate/close it via delete-process */
2958
2959 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2960 0, MANY, 0,
2961 doc: /* Create and return a network server or client process.
2962
2963 In Emacs, network connections are represented by process objects, so
2964 input and output work as for subprocesses and `delete-process' closes
2965 a network connection. However, a network process has no process id,
2966 it cannot be signaled, and the status codes are different from normal
2967 processes.
2968
2969 Arguments are specified as keyword/argument pairs. The following
2970 arguments are defined:
2971
2972 :name NAME -- NAME is name for process. It is modified if necessary
2973 to make it unique.
2974
2975 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2976 with the process. Process output goes at end of that buffer, unless
2977 you specify an output stream or filter function to handle the output.
2978 BUFFER may be also nil, meaning that this process is not associated
2979 with any buffer.
2980
2981 :host HOST -- HOST is name of the host to connect to, or its IP
2982 address. The symbol `local' specifies the local host. If specified
2983 for a server process, it must be a valid name or address for the local
2984 host, and only clients connecting to that address will be accepted.
2985
2986 :service SERVICE -- SERVICE is name of the service desired, or an
2987 integer specifying a port number to connect to. If SERVICE is t,
2988 a random port number is selected for the server. (If Emacs was
2989 compiled with getaddrinfo, a port number can also be specified as a
2990 string, e.g. "80", as well as an integer. This is not portable.)
2991
2992 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2993 stream type connection, `datagram' creates a datagram type connection,
2994 `seqpacket' creates a reliable datagram connection.
2995
2996 :family FAMILY -- FAMILY is the address (and protocol) family for the
2997 service specified by HOST and SERVICE. The default (nil) is to use
2998 whatever address family (IPv4 or IPv6) that is defined for the host
2999 and port number specified by HOST and SERVICE. Other address families
3000 supported are:
3001 local -- for a local (i.e. UNIX) address specified by SERVICE.
3002 ipv4 -- use IPv4 address family only.
3003 ipv6 -- use IPv6 address family only.
3004
3005 :local ADDRESS -- ADDRESS is the local address used for the connection.
3006 This parameter is ignored when opening a client process. When specified
3007 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3008
3009 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3010 connection. This parameter is ignored when opening a stream server
3011 process. For a datagram server process, it specifies the initial
3012 setting of the remote datagram address. When specified for a client
3013 process, the FAMILY, HOST, and SERVICE args are ignored.
3014
3015 The format of ADDRESS depends on the address family:
3016 - An IPv4 address is represented as an vector of integers [A B C D P]
3017 corresponding to numeric IP address A.B.C.D and port number P.
3018 - A local address is represented as a string with the address in the
3019 local address space.
3020 - An "unsupported family" address is represented by a cons (F . AV)
3021 where F is the family number and AV is a vector containing the socket
3022 address data with one element per address data byte. Do not rely on
3023 this format in portable code, as it may depend on implementation
3024 defined constants, data sizes, and data structure alignment.
3025
3026 :coding CODING -- If CODING is a symbol, it specifies the coding
3027 system used for both reading and writing for this process. If CODING
3028 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3029 ENCODING is used for writing.
3030
3031 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
3032 return without waiting for the connection to complete; instead, the
3033 sentinel function will be called with second arg matching "open" (if
3034 successful) or "failed" when the connect completes. Default is to use
3035 a blocking connect (i.e. wait) for stream type connections.
3036
3037 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3038 running when Emacs is exited.
3039
3040 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3041 In the stopped state, a server process does not accept new
3042 connections, and a client process does not handle incoming traffic.
3043 The stopped state is cleared by `continue-process' and set by
3044 `stop-process'.
3045
3046 :filter FILTER -- Install FILTER as the process filter.
3047
3048 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3049 process filter are multibyte, otherwise they are unibyte.
3050 If this keyword is not specified, the strings are multibyte if
3051 `default-enable-multibyte-characters' is non-nil.
3052
3053 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3054
3055 :log LOG -- Install LOG as the server process log function. This
3056 function is called when the server accepts a network connection from a
3057 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3058 is the server process, CLIENT is the new process for the connection,
3059 and MESSAGE is a string.
3060
3061 :plist PLIST -- Install PLIST as the new process' initial plist.
3062
3063 :server QLEN -- if QLEN is non-nil, create a server process for the
3064 specified FAMILY, SERVICE, and connection type (stream or datagram).
3065 If QLEN is an integer, it is used as the max. length of the server's
3066 pending connection queue (also known as the backlog); the default
3067 queue length is 5. Default is to create a client process.
3068
3069 The following network options can be specified for this connection:
3070
3071 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3072 :dontroute BOOL -- Only send to directly connected hosts.
3073 :keepalive BOOL -- Send keep-alive messages on network stream.
3074 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3075 :oobinline BOOL -- Place out-of-band data in receive data stream.
3076 :priority INT -- Set protocol defined priority for sent packets.
3077 :reuseaddr BOOL -- Allow reusing a recently used local address
3078 (this is allowed by default for a server process).
3079 :bindtodevice NAME -- bind to interface NAME. Using this may require
3080 special privileges on some systems.
3081
3082 Consult the relevant system programmer's manual pages for more
3083 information on using these options.
3084
3085
3086 A server process will listen for and accept connections from clients.
3087 When a client connection is accepted, a new network process is created
3088 for the connection with the following parameters:
3089
3090 - The client's process name is constructed by concatenating the server
3091 process' NAME and a client identification string.
3092 - If the FILTER argument is non-nil, the client process will not get a
3093 separate process buffer; otherwise, the client's process buffer is a newly
3094 created buffer named after the server process' BUFFER name or process
3095 NAME concatenated with the client identification string.
3096 - The connection type and the process filter and sentinel parameters are
3097 inherited from the server process' TYPE, FILTER and SENTINEL.
3098 - The client process' contact info is set according to the client's
3099 addressing information (typically an IP address and a port number).
3100 - The client process' plist is initialized from the server's plist.
3101
3102 Notice that the FILTER and SENTINEL args are never used directly by
3103 the server process. Also, the BUFFER argument is not used directly by
3104 the server process, but via the optional :log function, accepted (and
3105 failed) connections may be logged in the server process' buffer.
3106
3107 The original argument list, modified with the actual connection
3108 information, is available via the `process-contact' function.
3109
3110 usage: (make-network-process &rest ARGS) */)
3111 (int nargs, Lisp_Object *args)
3112 {
3113 Lisp_Object proc;
3114 Lisp_Object contact;
3115 struct Lisp_Process *p;
3116 #ifdef HAVE_GETADDRINFO
3117 struct addrinfo ai, *res, *lres;
3118 struct addrinfo hints;
3119 const char *portstring;
3120 char portbuf[128];
3121 #else /* HAVE_GETADDRINFO */
3122 struct _emacs_addrinfo
3123 {
3124 int ai_family;
3125 int ai_socktype;
3126 int ai_protocol;
3127 int ai_addrlen;
3128 struct sockaddr *ai_addr;
3129 struct _emacs_addrinfo *ai_next;
3130 } ai, *res, *lres;
3131 #endif /* HAVE_GETADDRINFO */
3132 struct sockaddr_in address_in;
3133 #ifdef HAVE_LOCAL_SOCKETS
3134 struct sockaddr_un address_un;
3135 #endif
3136 int port;
3137 int ret = 0;
3138 int xerrno = 0;
3139 int s = -1, outch, inch;
3140 struct gcpro gcpro1;
3141 int count = SPECPDL_INDEX ();
3142 int count1;
3143 Lisp_Object QCaddress; /* one of QClocal or QCremote */
3144 Lisp_Object tem;
3145 Lisp_Object name, buffer, host, service, address;
3146 Lisp_Object filter, sentinel;
3147 int is_non_blocking_client = 0;
3148 int is_server = 0, backlog = 5;
3149 int socktype;
3150 int family = -1;
3151
3152 if (nargs == 0)
3153 return Qnil;
3154
3155 /* Save arguments for process-contact and clone-process. */
3156 contact = Flist (nargs, args);
3157 GCPRO1 (contact);
3158
3159 #ifdef WINDOWSNT
3160 /* Ensure socket support is loaded if available. */
3161 init_winsock (TRUE);
3162 #endif
3163
3164 /* :type TYPE (nil: stream, datagram */
3165 tem = Fplist_get (contact, QCtype);
3166 if (NILP (tem))
3167 socktype = SOCK_STREAM;
3168 #ifdef DATAGRAM_SOCKETS
3169 else if (EQ (tem, Qdatagram))
3170 socktype = SOCK_DGRAM;
3171 #endif
3172 #ifdef HAVE_SEQPACKET
3173 else if (EQ (tem, Qseqpacket))
3174 socktype = SOCK_SEQPACKET;
3175 #endif
3176 else
3177 error ("Unsupported connection type");
3178
3179 /* :server BOOL */
3180 tem = Fplist_get (contact, QCserver);
3181 if (!NILP (tem))
3182 {
3183 /* Don't support network sockets when non-blocking mode is
3184 not available, since a blocked Emacs is not useful. */
3185 #if !defined(O_NONBLOCK) && !defined(O_NDELAY)
3186 error ("Network servers not supported");
3187 #else
3188 is_server = 1;
3189 if (INTEGERP (tem))
3190 backlog = XINT (tem);
3191 #endif
3192 }
3193
3194 /* Make QCaddress an alias for :local (server) or :remote (client). */
3195 QCaddress = is_server ? QClocal : QCremote;
3196
3197 /* :nowait BOOL */
3198 if (!is_server && socktype != SOCK_DGRAM
3199 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
3200 {
3201 #ifndef NON_BLOCKING_CONNECT
3202 error ("Non-blocking connect not supported");
3203 #else
3204 is_non_blocking_client = 1;
3205 #endif
3206 }
3207
3208 name = Fplist_get (contact, QCname);
3209 buffer = Fplist_get (contact, QCbuffer);
3210 filter = Fplist_get (contact, QCfilter);
3211 sentinel = Fplist_get (contact, QCsentinel);
3212
3213 CHECK_STRING (name);
3214
3215 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
3216 ai.ai_socktype = socktype;
3217 ai.ai_protocol = 0;
3218 ai.ai_next = NULL;
3219 res = &ai;
3220
3221 /* :local ADDRESS or :remote ADDRESS */
3222 address = Fplist_get (contact, QCaddress);
3223 if (!NILP (address))
3224 {
3225 host = service = Qnil;
3226
3227 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
3228 error ("Malformed :address");
3229 ai.ai_family = family;
3230 ai.ai_addr = alloca (ai.ai_addrlen);
3231 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
3232 goto open_socket;
3233 }
3234
3235 /* :family FAMILY -- nil (for Inet), local, or integer. */
3236 tem = Fplist_get (contact, QCfamily);
3237 if (NILP (tem))
3238 {
3239 #if defined(HAVE_GETADDRINFO) && defined(AF_INET6)
3240 family = AF_UNSPEC;
3241 #else
3242 family = AF_INET;
3243 #endif
3244 }
3245 #ifdef HAVE_LOCAL_SOCKETS
3246 else if (EQ (tem, Qlocal))
3247 family = AF_LOCAL;
3248 #endif
3249 #ifdef AF_INET6
3250 else if (EQ (tem, Qipv6))
3251 family = AF_INET6;
3252 #endif
3253 else if (EQ (tem, Qipv4))
3254 family = AF_INET;
3255 else if (INTEGERP (tem))
3256 family = XINT (tem);
3257 else
3258 error ("Unknown address family");
3259
3260 ai.ai_family = family;
3261
3262 /* :service SERVICE -- string, integer (port number), or t (random port). */
3263 service = Fplist_get (contact, QCservice);
3264
3265 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3266 host = Fplist_get (contact, QChost);
3267 if (!NILP (host))
3268 {
3269 if (EQ (host, Qlocal))
3270 /* Depending on setup, "localhost" may map to different IPv4 and/or
3271 IPv6 addresses, so it's better to be explicit. (Bug#6781) */
3272 host = build_string ("127.0.0.1");
3273 CHECK_STRING (host);
3274 }
3275
3276 #ifdef HAVE_LOCAL_SOCKETS
3277 if (family == AF_LOCAL)
3278 {
3279 if (!NILP (host))
3280 {
3281 message (":family local ignores the :host \"%s\" property",
3282 SDATA (host));
3283 contact = Fplist_put (contact, QChost, Qnil);
3284 host = Qnil;
3285 }
3286 CHECK_STRING (service);
3287 memset (&address_un, 0, sizeof address_un);
3288 address_un.sun_family = AF_LOCAL;
3289 strncpy (address_un.sun_path, SDATA (service), sizeof address_un.sun_path);
3290 ai.ai_addr = (struct sockaddr *) &address_un;
3291 ai.ai_addrlen = sizeof address_un;
3292 goto open_socket;
3293 }
3294 #endif
3295
3296 /* Slow down polling to every ten seconds.
3297 Some kernels have a bug which causes retrying connect to fail
3298 after a connect. Polling can interfere with gethostbyname too. */
3299 #ifdef POLL_FOR_INPUT
3300 if (socktype != SOCK_DGRAM)
3301 {
3302 record_unwind_protect (unwind_stop_other_atimers, Qnil);
3303 bind_polling_period (10);
3304 }
3305 #endif
3306
3307 #ifdef HAVE_GETADDRINFO
3308 /* If we have a host, use getaddrinfo to resolve both host and service.
3309 Otherwise, use getservbyname to lookup the service. */
3310 if (!NILP (host))
3311 {
3312
3313 /* SERVICE can either be a string or int.
3314 Convert to a C string for later use by getaddrinfo. */
3315 if (EQ (service, Qt))
3316 portstring = "0";
3317 else if (INTEGERP (service))
3318 {
3319 sprintf (portbuf, "%ld", (long) XINT (service));
3320 portstring = portbuf;
3321 }
3322 else
3323 {
3324 CHECK_STRING (service);
3325 portstring = SDATA (service);
3326 }
3327
3328 immediate_quit = 1;
3329 QUIT;
3330 memset (&hints, 0, sizeof (hints));
3331 hints.ai_flags = 0;
3332 hints.ai_family = family;
3333 hints.ai_socktype = socktype;
3334 hints.ai_protocol = 0;
3335
3336 #ifdef HAVE_RES_INIT
3337 res_init ();
3338 #endif
3339
3340 ret = getaddrinfo (SDATA (host), portstring, &hints, &res);
3341 if (ret)
3342 #ifdef HAVE_GAI_STRERROR
3343 error ("%s/%s %s", SDATA (host), portstring, gai_strerror (ret));
3344 #else
3345 error ("%s/%s getaddrinfo error %d", SDATA (host), portstring, ret);
3346 #endif
3347 immediate_quit = 0;
3348
3349 goto open_socket;
3350 }
3351 #endif /* HAVE_GETADDRINFO */
3352
3353 /* We end up here if getaddrinfo is not defined, or in case no hostname
3354 has been specified (e.g. for a local server process). */
3355
3356 if (EQ (service, Qt))
3357 port = 0;
3358 else if (INTEGERP (service))
3359 port = htons ((unsigned short) XINT (service));
3360 else
3361 {
3362 struct servent *svc_info;
3363 CHECK_STRING (service);
3364 svc_info = getservbyname (SDATA (service),
3365 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3366 if (svc_info == 0)
3367 error ("Unknown service: %s", SDATA (service));
3368 port = svc_info->s_port;
3369 }
3370
3371 memset (&address_in, 0, sizeof address_in);
3372 address_in.sin_family = family;
3373 address_in.sin_addr.s_addr = INADDR_ANY;
3374 address_in.sin_port = port;
3375
3376 #ifndef HAVE_GETADDRINFO
3377 if (!NILP (host))
3378 {
3379 struct hostent *host_info_ptr;
3380
3381 /* gethostbyname may fail with TRY_AGAIN, but we don't honour that,
3382 as it may `hang' Emacs for a very long time. */
3383 immediate_quit = 1;
3384 QUIT;
3385
3386 #ifdef HAVE_RES_INIT
3387 res_init ();
3388 #endif
3389
3390 host_info_ptr = gethostbyname (SDATA (host));
3391 immediate_quit = 0;
3392
3393 if (host_info_ptr)
3394 {
3395 memcpy (&address_in.sin_addr, host_info_ptr->h_addr,
3396 host_info_ptr->h_length);
3397 family = host_info_ptr->h_addrtype;
3398 address_in.sin_family = family;
3399 }
3400 else
3401 /* Attempt to interpret host as numeric inet address */
3402 {
3403 unsigned long numeric_addr;
3404 numeric_addr = inet_addr ((char *) SDATA (host));
3405 if (numeric_addr == -1)
3406 error ("Unknown host \"%s\"", SDATA (host));
3407
3408 memcpy (&address_in.sin_addr, &numeric_addr,
3409 sizeof (address_in.sin_addr));
3410 }
3411
3412 }
3413 #endif /* not HAVE_GETADDRINFO */
3414
3415 ai.ai_family = family;
3416 ai.ai_addr = (struct sockaddr *) &address_in;
3417 ai.ai_addrlen = sizeof address_in;
3418
3419 open_socket:
3420
3421 /* Do this in case we never enter the for-loop below. */
3422 count1 = SPECPDL_INDEX ();
3423 s = -1;
3424
3425 for (lres = res; lres; lres = lres->ai_next)
3426 {
3427 int optn, optbits;
3428
3429 retry_connect:
3430
3431 s = socket (lres->ai_family, lres->ai_socktype, lres->ai_protocol);
3432 if (s < 0)
3433 {
3434 xerrno = errno;
3435 continue;
3436 }
3437
3438 #ifdef DATAGRAM_SOCKETS
3439 if (!is_server && socktype == SOCK_DGRAM)
3440 break;
3441 #endif /* DATAGRAM_SOCKETS */
3442
3443 #ifdef NON_BLOCKING_CONNECT
3444 if (is_non_blocking_client)
3445 {
3446 #ifdef O_NONBLOCK
3447 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3448 #else
3449 ret = fcntl (s, F_SETFL, O_NDELAY);
3450 #endif
3451 if (ret < 0)
3452 {
3453 xerrno = errno;
3454 emacs_close (s);
3455 s = -1;
3456 continue;
3457 }
3458 }
3459 #endif
3460
3461 /* Make us close S if quit. */
3462 record_unwind_protect (close_file_unwind, make_number (s));
3463
3464 /* Parse network options in the arg list.
3465 We simply ignore anything which isn't a known option (including other keywords).
3466 An error is signaled if setting a known option fails. */
3467 for (optn = optbits = 0; optn < nargs-1; optn += 2)
3468 optbits |= set_socket_option (s, args[optn], args[optn+1]);
3469
3470 if (is_server)
3471 {
3472 /* Configure as a server socket. */
3473
3474 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3475 explicit :reuseaddr key to override this. */
3476 #ifdef HAVE_LOCAL_SOCKETS
3477 if (family != AF_LOCAL)
3478 #endif
3479 if (!(optbits & (1 << OPIX_REUSEADDR)))
3480 {
3481 int optval = 1;
3482 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3483 report_file_error ("Cannot set reuse option on server socket", Qnil);
3484 }
3485
3486 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3487 report_file_error ("Cannot bind server socket", Qnil);
3488
3489 #ifdef HAVE_GETSOCKNAME
3490 if (EQ (service, Qt))
3491 {
3492 struct sockaddr_in sa1;
3493 int len1 = sizeof (sa1);
3494 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3495 {
3496 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3497 service = make_number (ntohs (sa1.sin_port));
3498 contact = Fplist_put (contact, QCservice, service);
3499 }
3500 }
3501 #endif
3502
3503 if (socktype != SOCK_DGRAM && listen (s, backlog))
3504 report_file_error ("Cannot listen on server socket", Qnil);
3505
3506 break;
3507 }
3508
3509 immediate_quit = 1;
3510 QUIT;
3511
3512 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3513 xerrno = errno;
3514
3515 if (ret == 0 || xerrno == EISCONN)
3516 {
3517 /* The unwind-protect will be discarded afterwards.
3518 Likewise for immediate_quit. */
3519 break;
3520 }
3521
3522 #ifdef NON_BLOCKING_CONNECT
3523 #ifdef EINPROGRESS
3524 if (is_non_blocking_client && xerrno == EINPROGRESS)
3525 break;
3526 #else
3527 #ifdef EWOULDBLOCK
3528 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3529 break;
3530 #endif
3531 #endif
3532 #endif
3533
3534 #ifndef WINDOWSNT
3535 if (xerrno == EINTR)
3536 {
3537 /* Unlike most other syscalls connect() cannot be called
3538 again. (That would return EALREADY.) The proper way to
3539 wait for completion is select(). */
3540 int sc, len;
3541 SELECT_TYPE fdset;
3542 retry_select:
3543 FD_ZERO (&fdset);
3544 FD_SET (s, &fdset);
3545 QUIT;
3546 sc = select (s + 1, (SELECT_TYPE *)0, &fdset, (SELECT_TYPE *)0,
3547 (EMACS_TIME *)0);
3548 if (sc == -1)
3549 {
3550 if (errno == EINTR)
3551 goto retry_select;
3552 else
3553 report_file_error ("select failed", Qnil);
3554 }
3555 eassert (sc > 0);
3556
3557 len = sizeof xerrno;
3558 eassert (FD_ISSET (s, &fdset));
3559 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) == -1)
3560 report_file_error ("getsockopt failed", Qnil);
3561 if (xerrno)
3562 errno = xerrno, report_file_error ("error during connect", Qnil);
3563 else
3564 break;
3565 }
3566 #endif /* !WINDOWSNT */
3567
3568 immediate_quit = 0;
3569
3570 /* Discard the unwind protect closing S. */
3571 specpdl_ptr = specpdl + count1;
3572 emacs_close (s);
3573 s = -1;
3574
3575 #ifdef WINDOWSNT
3576 if (xerrno == EINTR)
3577 goto retry_connect;
3578 #endif
3579 }
3580
3581 if (s >= 0)
3582 {
3583 #ifdef DATAGRAM_SOCKETS
3584 if (socktype == SOCK_DGRAM)
3585 {
3586 if (datagram_address[s].sa)
3587 abort ();
3588 datagram_address[s].sa = (struct sockaddr *) xmalloc (lres->ai_addrlen);
3589 datagram_address[s].len = lres->ai_addrlen;
3590 if (is_server)
3591 {
3592 Lisp_Object remote;
3593 memset (datagram_address[s].sa, 0, lres->ai_addrlen);
3594 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3595 {
3596 int rfamily, rlen;
3597 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3598 if (rfamily == lres->ai_family && rlen == lres->ai_addrlen)
3599 conv_lisp_to_sockaddr (rfamily, remote,
3600 datagram_address[s].sa, rlen);
3601 }
3602 }
3603 else
3604 memcpy (datagram_address[s].sa, lres->ai_addr, lres->ai_addrlen);
3605 }
3606 #endif
3607 contact = Fplist_put (contact, QCaddress,
3608 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3609 #ifdef HAVE_GETSOCKNAME
3610 if (!is_server)
3611 {
3612 struct sockaddr_in sa1;
3613 int len1 = sizeof (sa1);
3614 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3615 contact = Fplist_put (contact, QClocal,
3616 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3617 }
3618 #endif
3619 }
3620
3621 immediate_quit = 0;
3622
3623 #ifdef HAVE_GETADDRINFO
3624 if (res != &ai)
3625 {
3626 BLOCK_INPUT;
3627 freeaddrinfo (res);
3628 UNBLOCK_INPUT;
3629 }
3630 #endif
3631
3632 /* Discard the unwind protect for closing S, if any. */
3633 specpdl_ptr = specpdl + count1;
3634
3635 /* Unwind bind_polling_period and request_sigio. */
3636 unbind_to (count, Qnil);
3637
3638 if (s < 0)
3639 {
3640 /* If non-blocking got this far - and failed - assume non-blocking is
3641 not supported after all. This is probably a wrong assumption, but
3642 the normal blocking calls to open-network-stream handles this error
3643 better. */
3644 if (is_non_blocking_client)
3645 return Qnil;
3646
3647 errno = xerrno;
3648 if (is_server)
3649 report_file_error ("make server process failed", contact);
3650 else
3651 report_file_error ("make client process failed", contact);
3652 }
3653
3654 inch = s;
3655 outch = s;
3656
3657 if (!NILP (buffer))
3658 buffer = Fget_buffer_create (buffer);
3659 proc = make_process (name);
3660
3661 chan_process[inch] = proc;
3662
3663 #ifdef O_NONBLOCK
3664 fcntl (inch, F_SETFL, O_NONBLOCK);
3665 #else
3666 #ifdef O_NDELAY
3667 fcntl (inch, F_SETFL, O_NDELAY);
3668 #endif
3669 #endif
3670
3671 p = XPROCESS (proc);
3672
3673 p->childp = contact;
3674 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
3675 p->type = Qnetwork;
3676
3677 p->buffer = buffer;
3678 p->sentinel = sentinel;
3679 p->filter = filter;
3680 p->log = Fplist_get (contact, QClog);
3681 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3682 p->kill_without_query = 1;
3683 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3684 p->command = Qt;
3685 p->pid = 0;
3686 p->infd = inch;
3687 p->outfd = outch;
3688 if (is_server && socktype != SOCK_DGRAM)
3689 p->status = Qlisten;
3690
3691 /* Make the process marker point into the process buffer (if any). */
3692 if (BUFFERP (buffer))
3693 set_marker_both (p->mark, buffer,
3694 BUF_ZV (XBUFFER (buffer)),
3695 BUF_ZV_BYTE (XBUFFER (buffer)));
3696
3697 #ifdef NON_BLOCKING_CONNECT
3698 if (is_non_blocking_client)
3699 {
3700 /* We may get here if connect did succeed immediately. However,
3701 in that case, we still need to signal this like a non-blocking
3702 connection. */
3703 p->status = Qconnect;
3704 if (!FD_ISSET (inch, &connect_wait_mask))
3705 {
3706 FD_SET (inch, &connect_wait_mask);
3707 FD_SET (inch, &write_mask);
3708 num_pending_connects++;
3709 }
3710 }
3711 else
3712 #endif
3713 /* A server may have a client filter setting of Qt, but it must
3714 still listen for incoming connects unless it is stopped. */
3715 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3716 || (EQ (p->status, Qlisten) && NILP (p->command)))
3717 {
3718 FD_SET (inch, &input_wait_mask);
3719 FD_SET (inch, &non_keyboard_wait_mask);
3720 }
3721
3722 if (inch > max_process_desc)
3723 max_process_desc = inch;
3724
3725 tem = Fplist_member (contact, QCcoding);
3726 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3727 tem = Qnil; /* No error message (too late!). */
3728
3729 {
3730 /* Setup coding systems for communicating with the network stream. */
3731 struct gcpro gcpro1;
3732 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3733 Lisp_Object coding_systems = Qt;
3734 Lisp_Object args[5], val;
3735
3736 if (!NILP (tem))
3737 {
3738 val = XCAR (XCDR (tem));
3739 if (CONSP (val))
3740 val = XCAR (val);
3741 }
3742 else if (!NILP (Vcoding_system_for_read))
3743 val = Vcoding_system_for_read;
3744 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
3745 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
3746 /* We dare not decode end-of-line format by setting VAL to
3747 Qraw_text, because the existing Emacs Lisp libraries
3748 assume that they receive bare code including a sequene of
3749 CR LF. */
3750 val = Qnil;
3751 else
3752 {
3753 if (NILP (host) || NILP (service))
3754 coding_systems = Qnil;
3755 else
3756 {
3757 args[0] = Qopen_network_stream, args[1] = name,
3758 args[2] = buffer, args[3] = host, args[4] = service;
3759 GCPRO1 (proc);
3760 coding_systems = Ffind_operation_coding_system (5, args);
3761 UNGCPRO;
3762 }
3763 if (CONSP (coding_systems))
3764 val = XCAR (coding_systems);
3765 else if (CONSP (Vdefault_process_coding_system))
3766 val = XCAR (Vdefault_process_coding_system);
3767 else
3768 val = Qnil;
3769 }
3770 p->decode_coding_system = val;
3771
3772 if (!NILP (tem))
3773 {
3774 val = XCAR (XCDR (tem));
3775 if (CONSP (val))
3776 val = XCDR (val);
3777 }
3778 else if (!NILP (Vcoding_system_for_write))
3779 val = Vcoding_system_for_write;
3780 else if (NILP (current_buffer->enable_multibyte_characters))
3781 val = Qnil;
3782 else
3783 {
3784 if (EQ (coding_systems, Qt))
3785 {
3786 if (NILP (host) || NILP (service))
3787 coding_systems = Qnil;
3788 else
3789 {
3790 args[0] = Qopen_network_stream, args[1] = name,
3791 args[2] = buffer, args[3] = host, args[4] = service;
3792 GCPRO1 (proc);
3793 coding_systems = Ffind_operation_coding_system (5, args);
3794 UNGCPRO;
3795 }
3796 }
3797 if (CONSP (coding_systems))
3798 val = XCDR (coding_systems);
3799 else if (CONSP (Vdefault_process_coding_system))
3800 val = XCDR (Vdefault_process_coding_system);
3801 else
3802 val = Qnil;
3803 }
3804 p->encode_coding_system = val;
3805 }
3806 setup_process_coding_systems (proc);
3807
3808 p->decoding_buf = make_uninit_string (0);
3809 p->decoding_carryover = 0;
3810 p->encoding_buf = make_uninit_string (0);
3811
3812 p->inherit_coding_system_flag
3813 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3814
3815 UNGCPRO;
3816 return proc;
3817 }
3818
3819 \f
3820 #if defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H)
3821
3822 #ifdef SIOCGIFCONF
3823 DEFUN ("network-interface-list", Fnetwork_interface_list, Snetwork_interface_list, 0, 0, 0,
3824 doc: /* Return an alist of all network interfaces and their network address.
3825 Each element is a cons, the car of which is a string containing the
3826 interface name, and the cdr is the network address in internal
3827 format; see the description of ADDRESS in `make-network-process'. */)
3828 (void)
3829 {
3830 struct ifconf ifconf;
3831 struct ifreq *ifreqs = NULL;
3832 int ifaces = 0;
3833 int buf_size, s;
3834 Lisp_Object res;
3835
3836 s = socket (AF_INET, SOCK_STREAM, 0);
3837 if (s < 0)
3838 return Qnil;
3839
3840 again:
3841 ifaces += 25;
3842 buf_size = ifaces * sizeof (ifreqs[0]);
3843 ifreqs = (struct ifreq *)xrealloc(ifreqs, buf_size);
3844 if (!ifreqs)
3845 {
3846 close (s);
3847 return Qnil;
3848 }
3849
3850 ifconf.ifc_len = buf_size;
3851 ifconf.ifc_req = ifreqs;
3852 if (ioctl (s, SIOCGIFCONF, &ifconf))
3853 {
3854 close (s);
3855 return Qnil;
3856 }
3857
3858 if (ifconf.ifc_len == buf_size)
3859 goto again;
3860
3861 close (s);
3862 ifaces = ifconf.ifc_len / sizeof (ifreqs[0]);
3863
3864 res = Qnil;
3865 while (--ifaces >= 0)
3866 {
3867 struct ifreq *ifq = &ifreqs[ifaces];
3868 char namebuf[sizeof (ifq->ifr_name) + 1];
3869 if (ifq->ifr_addr.sa_family != AF_INET)
3870 continue;
3871 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
3872 namebuf[sizeof (ifq->ifr_name)] = 0;
3873 res = Fcons (Fcons (build_string (namebuf),
3874 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3875 sizeof (struct sockaddr))),
3876 res);
3877 }
3878
3879 return res;
3880 }
3881 #endif /* SIOCGIFCONF */
3882
3883 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
3884
3885 struct ifflag_def {
3886 int flag_bit;
3887 const char *flag_sym;
3888 };
3889
3890 static const struct ifflag_def ifflag_table[] = {
3891 #ifdef IFF_UP
3892 { IFF_UP, "up" },
3893 #endif
3894 #ifdef IFF_BROADCAST
3895 { IFF_BROADCAST, "broadcast" },
3896 #endif
3897 #ifdef IFF_DEBUG
3898 { IFF_DEBUG, "debug" },
3899 #endif
3900 #ifdef IFF_LOOPBACK
3901 { IFF_LOOPBACK, "loopback" },
3902 #endif
3903 #ifdef IFF_POINTOPOINT
3904 { IFF_POINTOPOINT, "pointopoint" },
3905 #endif
3906 #ifdef IFF_RUNNING
3907 { IFF_RUNNING, "running" },
3908 #endif
3909 #ifdef IFF_NOARP
3910 { IFF_NOARP, "noarp" },
3911 #endif
3912 #ifdef IFF_PROMISC
3913 { IFF_PROMISC, "promisc" },
3914 #endif
3915 #ifdef IFF_NOTRAILERS
3916 { IFF_NOTRAILERS, "notrailers" },
3917 #endif
3918 #ifdef IFF_ALLMULTI
3919 { IFF_ALLMULTI, "allmulti" },
3920 #endif
3921 #ifdef IFF_MASTER
3922 { IFF_MASTER, "master" },
3923 #endif
3924 #ifdef IFF_SLAVE
3925 { IFF_SLAVE, "slave" },
3926 #endif
3927 #ifdef IFF_MULTICAST
3928 { IFF_MULTICAST, "multicast" },
3929 #endif
3930 #ifdef IFF_PORTSEL
3931 { IFF_PORTSEL, "portsel" },
3932 #endif
3933 #ifdef IFF_AUTOMEDIA
3934 { IFF_AUTOMEDIA, "automedia" },
3935 #endif
3936 #ifdef IFF_DYNAMIC
3937 { IFF_DYNAMIC, "dynamic" },
3938 #endif
3939 #ifdef IFF_OACTIVE
3940 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress */
3941 #endif
3942 #ifdef IFF_SIMPLEX
3943 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions */
3944 #endif
3945 #ifdef IFF_LINK0
3946 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit */
3947 #endif
3948 #ifdef IFF_LINK1
3949 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit */
3950 #endif
3951 #ifdef IFF_LINK2
3952 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit */
3953 #endif
3954 { 0, 0 }
3955 };
3956
3957 DEFUN ("network-interface-info", Fnetwork_interface_info, Snetwork_interface_info, 1, 1, 0,
3958 doc: /* Return information about network interface named IFNAME.
3959 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3960 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3961 NETMASK is the layer 3 network mask, HWADDR is the layer 2 addres, and
3962 FLAGS is the current flags of the interface. */)
3963 (Lisp_Object ifname)
3964 {
3965 struct ifreq rq;
3966 Lisp_Object res = Qnil;
3967 Lisp_Object elt;
3968 int s;
3969 int any = 0;
3970
3971 CHECK_STRING (ifname);
3972
3973 memset (rq.ifr_name, 0, sizeof rq.ifr_name);
3974 strncpy (rq.ifr_name, SDATA (ifname), sizeof (rq.ifr_name));
3975
3976 s = socket (AF_INET, SOCK_STREAM, 0);
3977 if (s < 0)
3978 return Qnil;
3979
3980 elt = Qnil;
3981 #if defined(SIOCGIFFLAGS) && defined(HAVE_STRUCT_IFREQ_IFR_FLAGS)
3982 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
3983 {
3984 int flags = rq.ifr_flags;
3985 const struct ifflag_def *fp;
3986 int fnum;
3987
3988 any++;
3989 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
3990 {
3991 if (flags & fp->flag_bit)
3992 {
3993 elt = Fcons (intern (fp->flag_sym), elt);
3994 flags -= fp->flag_bit;
3995 }
3996 }
3997 for (fnum = 0; flags && fnum < 32; fnum++)
3998 {
3999 if (flags & (1 << fnum))
4000 {
4001 elt = Fcons (make_number (fnum), elt);
4002 }
4003 }
4004 }
4005 #endif
4006 res = Fcons (elt, res);
4007
4008 elt = Qnil;
4009 #if defined(SIOCGIFHWADDR) && defined(HAVE_STRUCT_IFREQ_IFR_HWADDR)
4010 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
4011 {
4012 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4013 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4014 int n;
4015
4016 any++;
4017 for (n = 0; n < 6; n++)
4018 p->contents[n] = make_number (((unsigned char *)&rq.ifr_hwaddr.sa_data[0])[n]);
4019 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
4020 }
4021 #endif
4022 res = Fcons (elt, res);
4023
4024 elt = Qnil;
4025 #if defined(SIOCGIFNETMASK) && (defined(HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined(HAVE_STRUCT_IFREQ_IFR_ADDR))
4026 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
4027 {
4028 any++;
4029 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4030 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
4031 #else
4032 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4033 #endif
4034 }
4035 #endif
4036 res = Fcons (elt, res);
4037
4038 elt = Qnil;
4039 #if defined(SIOCGIFBRDADDR) && defined(HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4040 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
4041 {
4042 any++;
4043 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
4044 }
4045 #endif
4046 res = Fcons (elt, res);
4047
4048 elt = Qnil;
4049 #if defined(SIOCGIFADDR) && defined(HAVE_STRUCT_IFREQ_IFR_ADDR)
4050 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
4051 {
4052 any++;
4053 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4054 }
4055 #endif
4056 res = Fcons (elt, res);
4057
4058 close (s);
4059
4060 return any ? res : Qnil;
4061 }
4062 #endif
4063 #endif /* defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H) */
4064
4065 /* Turn off input and output for process PROC. */
4066
4067 void
4068 deactivate_process (Lisp_Object proc)
4069 {
4070 register int inchannel, outchannel;
4071 register struct Lisp_Process *p = XPROCESS (proc);
4072
4073 inchannel = p->infd;
4074 outchannel = p->outfd;
4075
4076 #ifdef ADAPTIVE_READ_BUFFERING
4077 if (p->read_output_delay > 0)
4078 {
4079 if (--process_output_delay_count < 0)
4080 process_output_delay_count = 0;
4081 p->read_output_delay = 0;
4082 p->read_output_skip = 0;
4083 }
4084 #endif
4085
4086 if (inchannel >= 0)
4087 {
4088 /* Beware SIGCHLD hereabouts. */
4089 flush_pending_output (inchannel);
4090 emacs_close (inchannel);
4091 if (outchannel >= 0 && outchannel != inchannel)
4092 emacs_close (outchannel);
4093
4094 p->infd = -1;
4095 p->outfd = -1;
4096 #ifdef DATAGRAM_SOCKETS
4097 if (DATAGRAM_CHAN_P (inchannel))
4098 {
4099 xfree (datagram_address[inchannel].sa);
4100 datagram_address[inchannel].sa = 0;
4101 datagram_address[inchannel].len = 0;
4102 }
4103 #endif
4104 chan_process[inchannel] = Qnil;
4105 FD_CLR (inchannel, &input_wait_mask);
4106 FD_CLR (inchannel, &non_keyboard_wait_mask);
4107 #ifdef NON_BLOCKING_CONNECT
4108 if (FD_ISSET (inchannel, &connect_wait_mask))
4109 {
4110 FD_CLR (inchannel, &connect_wait_mask);
4111 FD_CLR (inchannel, &write_mask);
4112 if (--num_pending_connects < 0)
4113 abort ();
4114 }
4115 #endif
4116 if (inchannel == max_process_desc)
4117 {
4118 int i;
4119 /* We just closed the highest-numbered process input descriptor,
4120 so recompute the highest-numbered one now. */
4121 max_process_desc = 0;
4122 for (i = 0; i < MAXDESC; i++)
4123 if (!NILP (chan_process[i]))
4124 max_process_desc = i;
4125 }
4126 }
4127 }
4128
4129 \f
4130 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4131 0, 4, 0,
4132 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4133 It is read into the process' buffers or given to their filter functions.
4134 Non-nil arg PROCESS means do not return until some output has been received
4135 from PROCESS.
4136
4137 Non-nil second arg SECONDS and third arg MILLISEC are number of seconds
4138 and milliseconds to wait; return after that much time whether or not
4139 there is any subprocess output. If SECONDS is a floating point number,
4140 it specifies a fractional number of seconds to wait.
4141 The MILLISEC argument is obsolete and should be avoided.
4142
4143 If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
4144 from PROCESS, suspending reading output from other processes.
4145 If JUST-THIS-ONE is an integer, don't run any timers either.
4146 Return non-nil if we received any output before the timeout expired. */)
4147 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
4148 {
4149 int secs, usecs = 0;
4150
4151 if (! NILP (process))
4152 CHECK_PROCESS (process);
4153 else
4154 just_this_one = Qnil;
4155
4156 if (!NILP (millisec))
4157 { /* Obsolete calling convention using integers rather than floats. */
4158 CHECK_NUMBER (millisec);
4159 if (NILP (seconds))
4160 seconds = make_float (XINT (millisec) / 1000.0);
4161 else
4162 {
4163 CHECK_NUMBER (seconds);
4164 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4165 }
4166 }
4167
4168 if (!NILP (seconds))
4169 {
4170 if (INTEGERP (seconds))
4171 secs = XINT (seconds);
4172 else if (FLOATP (seconds))
4173 {
4174 double timeout = XFLOAT_DATA (seconds);
4175 secs = (int) timeout;
4176 usecs = (int) ((timeout - (double) secs) * 1000000);
4177 }
4178 else
4179 wrong_type_argument (Qnumberp, seconds);
4180
4181 if (secs < 0 || (secs == 0 && usecs == 0))
4182 secs = -1, usecs = 0;
4183 }
4184 else
4185 secs = NILP (process) ? -1 : 0;
4186
4187 return
4188 (wait_reading_process_output (secs, usecs, 0, 0,
4189 Qnil,
4190 !NILP (process) ? XPROCESS (process) : NULL,
4191 NILP (just_this_one) ? 0 :
4192 !INTEGERP (just_this_one) ? 1 : -1)
4193 ? Qt : Qnil);
4194 }
4195
4196 /* Accept a connection for server process SERVER on CHANNEL. */
4197
4198 static int connect_counter = 0;
4199
4200 static void
4201 server_accept_connection (Lisp_Object server, int channel)
4202 {
4203 Lisp_Object proc, caller, name, buffer;
4204 Lisp_Object contact, host, service;
4205 struct Lisp_Process *ps= XPROCESS (server);
4206 struct Lisp_Process *p;
4207 int s;
4208 union u_sockaddr {
4209 struct sockaddr sa;
4210 struct sockaddr_in in;
4211 #ifdef AF_INET6
4212 struct sockaddr_in6 in6;
4213 #endif
4214 #ifdef HAVE_LOCAL_SOCKETS
4215 struct sockaddr_un un;
4216 #endif
4217 } saddr;
4218 int len = sizeof saddr;
4219
4220 s = accept (channel, &saddr.sa, &len);
4221
4222 if (s < 0)
4223 {
4224 int code = errno;
4225
4226 if (code == EAGAIN)
4227 return;
4228 #ifdef EWOULDBLOCK
4229 if (code == EWOULDBLOCK)
4230 return;
4231 #endif
4232
4233 if (!NILP (ps->log))
4234 call3 (ps->log, server, Qnil,
4235 concat3 (build_string ("accept failed with code"),
4236 Fnumber_to_string (make_number (code)),
4237 build_string ("\n")));
4238 return;
4239 }
4240
4241 connect_counter++;
4242
4243 /* Setup a new process to handle the connection. */
4244
4245 /* Generate a unique identification of the caller, and build contact
4246 information for this process. */
4247 host = Qt;
4248 service = Qnil;
4249 switch (saddr.sa.sa_family)
4250 {
4251 case AF_INET:
4252 {
4253 Lisp_Object args[5];
4254 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4255 args[0] = build_string ("%d.%d.%d.%d");
4256 args[1] = make_number (*ip++);
4257 args[2] = make_number (*ip++);
4258 args[3] = make_number (*ip++);
4259 args[4] = make_number (*ip++);
4260 host = Fformat (5, args);
4261 service = make_number (ntohs (saddr.in.sin_port));
4262
4263 args[0] = build_string (" <%s:%d>");
4264 args[1] = host;
4265 args[2] = service;
4266 caller = Fformat (3, args);
4267 }
4268 break;
4269
4270 #ifdef AF_INET6
4271 case AF_INET6:
4272 {
4273 Lisp_Object args[9];
4274 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4275 int i;
4276 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4277 for (i = 0; i < 8; i++)
4278 args[i+1] = make_number (ntohs (ip6[i]));
4279 host = Fformat (9, args);
4280 service = make_number (ntohs (saddr.in.sin_port));
4281
4282 args[0] = build_string (" <[%s]:%d>");
4283 args[1] = host;
4284 args[2] = service;
4285 caller = Fformat (3, args);
4286 }
4287 break;
4288 #endif
4289
4290 #ifdef HAVE_LOCAL_SOCKETS
4291 case AF_LOCAL:
4292 #endif
4293 default:
4294 caller = Fnumber_to_string (make_number (connect_counter));
4295 caller = concat3 (build_string (" <"), caller, build_string (">"));
4296 break;
4297 }
4298
4299 /* Create a new buffer name for this process if it doesn't have a
4300 filter. The new buffer name is based on the buffer name or
4301 process name of the server process concatenated with the caller
4302 identification. */
4303
4304 if (!NILP (ps->filter) && !EQ (ps->filter, Qt))
4305 buffer = Qnil;
4306 else
4307 {
4308 buffer = ps->buffer;
4309 if (!NILP (buffer))
4310 buffer = Fbuffer_name (buffer);
4311 else
4312 buffer = ps->name;
4313 if (!NILP (buffer))
4314 {
4315 buffer = concat2 (buffer, caller);
4316 buffer = Fget_buffer_create (buffer);
4317 }
4318 }
4319
4320 /* Generate a unique name for the new server process. Combine the
4321 server process name with the caller identification. */
4322
4323 name = concat2 (ps->name, caller);
4324 proc = make_process (name);
4325
4326 chan_process[s] = proc;
4327
4328 #ifdef O_NONBLOCK
4329 fcntl (s, F_SETFL, O_NONBLOCK);
4330 #else
4331 #ifdef O_NDELAY
4332 fcntl (s, F_SETFL, O_NDELAY);
4333 #endif
4334 #endif
4335
4336 p = XPROCESS (proc);
4337
4338 /* Build new contact information for this setup. */
4339 contact = Fcopy_sequence (ps->childp);
4340 contact = Fplist_put (contact, QCserver, Qnil);
4341 contact = Fplist_put (contact, QChost, host);
4342 if (!NILP (service))
4343 contact = Fplist_put (contact, QCservice, service);
4344 contact = Fplist_put (contact, QCremote,
4345 conv_sockaddr_to_lisp (&saddr.sa, len));
4346 #ifdef HAVE_GETSOCKNAME
4347 len = sizeof saddr;
4348 if (getsockname (s, &saddr.sa, &len) == 0)
4349 contact = Fplist_put (contact, QClocal,
4350 conv_sockaddr_to_lisp (&saddr.sa, len));
4351 #endif
4352
4353 p->childp = contact;
4354 p->plist = Fcopy_sequence (ps->plist);
4355 p->type = Qnetwork;
4356
4357 p->buffer = buffer;
4358 p->sentinel = ps->sentinel;
4359 p->filter = ps->filter;
4360 p->command = Qnil;
4361 p->pid = 0;
4362 p->infd = s;
4363 p->outfd = s;
4364 p->status = Qrun;
4365
4366 /* Client processes for accepted connections are not stopped initially. */
4367 if (!EQ (p->filter, Qt))
4368 {
4369 FD_SET (s, &input_wait_mask);
4370 FD_SET (s, &non_keyboard_wait_mask);
4371 }
4372
4373 if (s > max_process_desc)
4374 max_process_desc = s;
4375
4376 /* Setup coding system for new process based on server process.
4377 This seems to be the proper thing to do, as the coding system
4378 of the new process should reflect the settings at the time the
4379 server socket was opened; not the current settings. */
4380
4381 p->decode_coding_system = ps->decode_coding_system;
4382 p->encode_coding_system = ps->encode_coding_system;
4383 setup_process_coding_systems (proc);
4384
4385 p->decoding_buf = make_uninit_string (0);
4386 p->decoding_carryover = 0;
4387 p->encoding_buf = make_uninit_string (0);
4388
4389 p->inherit_coding_system_flag
4390 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4391
4392 if (!NILP (ps->log))
4393 call3 (ps->log, server, proc,
4394 concat3 (build_string ("accept from "),
4395 (STRINGP (host) ? host : build_string ("-")),
4396 build_string ("\n")));
4397
4398 if (!NILP (p->sentinel))
4399 exec_sentinel (proc,
4400 concat3 (build_string ("open from "),
4401 (STRINGP (host) ? host : build_string ("-")),
4402 build_string ("\n")));
4403 }
4404
4405 /* This variable is different from waiting_for_input in keyboard.c.
4406 It is used to communicate to a lisp process-filter/sentinel (via the
4407 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4408 for user-input when that process-filter was called.
4409 waiting_for_input cannot be used as that is by definition 0 when
4410 lisp code is being evalled.
4411 This is also used in record_asynch_buffer_change.
4412 For that purpose, this must be 0
4413 when not inside wait_reading_process_output. */
4414 static int waiting_for_user_input_p;
4415
4416 static Lisp_Object
4417 wait_reading_process_output_unwind (Lisp_Object data)
4418 {
4419 waiting_for_user_input_p = XINT (data);
4420 return Qnil;
4421 }
4422
4423 /* This is here so breakpoints can be put on it. */
4424 static void
4425 wait_reading_process_output_1 (void)
4426 {
4427 }
4428
4429 /* Use a wrapper around select to work around a bug in gdb 5.3.
4430 Normally, the wrapper is optimized away by inlining.
4431
4432 If emacs is stopped inside select, the gdb backtrace doesn't
4433 show the function which called select, so it is practically
4434 impossible to step through wait_reading_process_output. */
4435
4436 #ifndef select
4437 static INLINE int
4438 select_wrapper (int n, fd_set *rfd, fd_set *wfd, fd_set *xfd, struct timeval *tmo)
4439 {
4440 return select (n, rfd, wfd, xfd, tmo);
4441 }
4442 #define select select_wrapper
4443 #endif
4444
4445 /* Read and dispose of subprocess output while waiting for timeout to
4446 elapse and/or keyboard input to be available.
4447
4448 TIME_LIMIT is:
4449 timeout in seconds, or
4450 zero for no limit, or
4451 -1 means gobble data immediately available but don't wait for any.
4452
4453 MICROSECS is:
4454 an additional duration to wait, measured in microseconds.
4455 If this is nonzero and time_limit is 0, then the timeout
4456 consists of MICROSECS only.
4457
4458 READ_KBD is a lisp value:
4459 0 to ignore keyboard input, or
4460 1 to return when input is available, or
4461 -1 meaning caller will actually read the input, so don't throw to
4462 the quit handler, or
4463
4464 DO_DISPLAY != 0 means redisplay should be done to show subprocess
4465 output that arrives.
4466
4467 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4468 (and gobble terminal input into the buffer if any arrives).
4469
4470 If WAIT_PROC is specified, wait until something arrives from that
4471 process. The return value is true if we read some input from
4472 that process.
4473
4474 If JUST_WAIT_PROC is non-nil, handle only output from WAIT_PROC
4475 (suspending output from other processes). A negative value
4476 means don't run any timers either.
4477
4478 If WAIT_PROC is specified, then the function returns true if we
4479 received input from that process before the timeout elapsed.
4480 Otherwise, return true if we received input from any process. */
4481
4482 int
4483 wait_reading_process_output (int time_limit, int microsecs, int read_kbd,
4484 int do_display,
4485 Lisp_Object wait_for_cell,
4486 struct Lisp_Process *wait_proc, int just_wait_proc)
4487 {
4488 register int channel, nfds;
4489 SELECT_TYPE Available;
4490 SELECT_TYPE Writeok;
4491 int check_write;
4492 int check_delay, no_avail;
4493 int xerrno;
4494 Lisp_Object proc;
4495 EMACS_TIME timeout, end_time;
4496 int wait_channel = -1;
4497 int got_some_input = 0;
4498 int count = SPECPDL_INDEX ();
4499
4500 FD_ZERO (&Available);
4501 FD_ZERO (&Writeok);
4502
4503 if (time_limit == 0 && microsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
4504 && !(CONSP (wait_proc->status) && EQ (XCAR (wait_proc->status), Qexit)))
4505 message ("Blocking call to accept-process-output with quit inhibited!!");
4506
4507 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4508 if (wait_proc != NULL)
4509 wait_channel = wait_proc->infd;
4510
4511 record_unwind_protect (wait_reading_process_output_unwind,
4512 make_number (waiting_for_user_input_p));
4513 waiting_for_user_input_p = read_kbd;
4514
4515 /* Since we may need to wait several times,
4516 compute the absolute time to return at. */
4517 if (time_limit || microsecs)
4518 {
4519 EMACS_GET_TIME (end_time);
4520 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
4521 EMACS_ADD_TIME (end_time, end_time, timeout);
4522 }
4523
4524 while (1)
4525 {
4526 int timeout_reduced_for_timers = 0;
4527
4528 /* If calling from keyboard input, do not quit
4529 since we want to return C-g as an input character.
4530 Otherwise, do pending quit if requested. */
4531 if (read_kbd >= 0)
4532 QUIT;
4533 #ifdef SYNC_INPUT
4534 else
4535 process_pending_signals ();
4536 #endif
4537
4538 /* Exit now if the cell we're waiting for became non-nil. */
4539 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4540 break;
4541
4542 /* Compute time from now till when time limit is up */
4543 /* Exit if already run out */
4544 if (time_limit == -1)
4545 {
4546 /* -1 specified for timeout means
4547 gobble output available now
4548 but don't wait at all. */
4549
4550 EMACS_SET_SECS_USECS (timeout, 0, 0);
4551 }
4552 else if (time_limit || microsecs)
4553 {
4554 EMACS_GET_TIME (timeout);
4555 EMACS_SUB_TIME (timeout, end_time, timeout);
4556 if (EMACS_TIME_NEG_P (timeout))
4557 break;
4558 }
4559 else
4560 {
4561 EMACS_SET_SECS_USECS (timeout, 100000, 0);
4562 }
4563
4564 /* Normally we run timers here.
4565 But not if wait_for_cell; in those cases,
4566 the wait is supposed to be short,
4567 and those callers cannot handle running arbitrary Lisp code here. */
4568 if (NILP (wait_for_cell)
4569 && just_wait_proc >= 0)
4570 {
4571 EMACS_TIME timer_delay;
4572
4573 do
4574 {
4575 int old_timers_run = timers_run;
4576 struct buffer *old_buffer = current_buffer;
4577 Lisp_Object old_window = selected_window;
4578
4579 timer_delay = timer_check (1);
4580
4581 /* If a timer has run, this might have changed buffers
4582 an alike. Make read_key_sequence aware of that. */
4583 if (timers_run != old_timers_run
4584 && (old_buffer != current_buffer
4585 || !EQ (old_window, selected_window))
4586 && waiting_for_user_input_p == -1)
4587 record_asynch_buffer_change ();
4588
4589 if (timers_run != old_timers_run && do_display)
4590 /* We must retry, since a timer may have requeued itself
4591 and that could alter the time_delay. */
4592 redisplay_preserve_echo_area (9);
4593 else
4594 break;
4595 }
4596 while (!detect_input_pending ());
4597
4598 /* If there is unread keyboard input, also return. */
4599 if (read_kbd != 0
4600 && requeued_events_pending_p ())
4601 break;
4602
4603 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
4604 {
4605 EMACS_TIME difference;
4606 EMACS_SUB_TIME (difference, timer_delay, timeout);
4607 if (EMACS_TIME_NEG_P (difference))
4608 {
4609 timeout = timer_delay;
4610 timeout_reduced_for_timers = 1;
4611 }
4612 }
4613 /* If time_limit is -1, we are not going to wait at all. */
4614 else if (time_limit != -1)
4615 {
4616 /* This is so a breakpoint can be put here. */
4617 wait_reading_process_output_1 ();
4618 }
4619 }
4620
4621 /* Cause C-g and alarm signals to take immediate action,
4622 and cause input available signals to zero out timeout.
4623
4624 It is important that we do this before checking for process
4625 activity. If we get a SIGCHLD after the explicit checks for
4626 process activity, timeout is the only way we will know. */
4627 if (read_kbd < 0)
4628 set_waiting_for_input (&timeout);
4629
4630 /* If status of something has changed, and no input is
4631 available, notify the user of the change right away. After
4632 this explicit check, we'll let the SIGCHLD handler zap
4633 timeout to get our attention. */
4634 if (update_tick != process_tick)
4635 {
4636 SELECT_TYPE Atemp;
4637 SELECT_TYPE Ctemp;
4638
4639 if (kbd_on_hold_p ())
4640 FD_ZERO (&Atemp);
4641 else
4642 Atemp = input_wait_mask;
4643 Ctemp = write_mask;
4644
4645 EMACS_SET_SECS_USECS (timeout, 0, 0);
4646 if ((select (max (max_process_desc, max_input_desc) + 1,
4647 &Atemp,
4648 #ifdef NON_BLOCKING_CONNECT
4649 (num_pending_connects > 0 ? &Ctemp : (SELECT_TYPE *)0),
4650 #else
4651 (SELECT_TYPE *)0,
4652 #endif
4653 (SELECT_TYPE *)0, &timeout)
4654 <= 0))
4655 {
4656 /* It's okay for us to do this and then continue with
4657 the loop, since timeout has already been zeroed out. */
4658 clear_waiting_for_input ();
4659 status_notify (NULL);
4660 if (do_display) redisplay_preserve_echo_area (13);
4661 }
4662 }
4663
4664 /* Don't wait for output from a non-running process. Just
4665 read whatever data has already been received. */
4666 if (wait_proc && wait_proc->raw_status_new)
4667 update_status (wait_proc);
4668 if (wait_proc
4669 && ! EQ (wait_proc->status, Qrun)
4670 && ! EQ (wait_proc->status, Qconnect))
4671 {
4672 int nread, total_nread = 0;
4673
4674 clear_waiting_for_input ();
4675 XSETPROCESS (proc, wait_proc);
4676
4677 /* Read data from the process, until we exhaust it. */
4678 while (wait_proc->infd >= 0)
4679 {
4680 nread = read_process_output (proc, wait_proc->infd);
4681
4682 if (nread == 0)
4683 break;
4684
4685 if (0 < nread)
4686 {
4687 total_nread += nread;
4688 got_some_input = 1;
4689 }
4690 #ifdef EIO
4691 else if (nread == -1 && EIO == errno)
4692 break;
4693 #endif
4694 #ifdef EAGAIN
4695 else if (nread == -1 && EAGAIN == errno)
4696 break;
4697 #endif
4698 #ifdef EWOULDBLOCK
4699 else if (nread == -1 && EWOULDBLOCK == errno)
4700 break;
4701 #endif
4702 }
4703 if (total_nread > 0 && do_display)
4704 redisplay_preserve_echo_area (10);
4705
4706 break;
4707 }
4708
4709 /* Wait till there is something to do */
4710
4711 if (wait_proc && just_wait_proc)
4712 {
4713 if (wait_proc->infd < 0) /* Terminated */
4714 break;
4715 FD_SET (wait_proc->infd, &Available);
4716 check_delay = 0;
4717 check_write = 0;
4718 }
4719 else if (!NILP (wait_for_cell))
4720 {
4721 Available = non_process_wait_mask;
4722 check_delay = 0;
4723 check_write = 0;
4724 }
4725 else
4726 {
4727 if (! read_kbd)
4728 Available = non_keyboard_wait_mask;
4729 else
4730 Available = input_wait_mask;
4731 Writeok = write_mask;
4732 #ifdef SELECT_CANT_DO_WRITE_MASK
4733 check_write = 0;
4734 #else
4735 check_write = 1;
4736 #endif
4737 check_delay = wait_channel >= 0 ? 0 : process_output_delay_count;
4738 }
4739
4740 /* If frame size has changed or the window is newly mapped,
4741 redisplay now, before we start to wait. There is a race
4742 condition here; if a SIGIO arrives between now and the select
4743 and indicates that a frame is trashed, the select may block
4744 displaying a trashed screen. */
4745 if (frame_garbaged && do_display)
4746 {
4747 clear_waiting_for_input ();
4748 redisplay_preserve_echo_area (11);
4749 if (read_kbd < 0)
4750 set_waiting_for_input (&timeout);
4751 }
4752
4753 no_avail = 0;
4754 if (read_kbd && detect_input_pending ())
4755 {
4756 nfds = 0;
4757 no_avail = 1;
4758 }
4759 else
4760 {
4761
4762 #ifdef ADAPTIVE_READ_BUFFERING
4763 /* Set the timeout for adaptive read buffering if any
4764 process has non-zero read_output_skip and non-zero
4765 read_output_delay, and we are not reading output for a
4766 specific wait_channel. It is not executed if
4767 Vprocess_adaptive_read_buffering is nil. */
4768 if (process_output_skip && check_delay > 0)
4769 {
4770 int usecs = EMACS_USECS (timeout);
4771 if (EMACS_SECS (timeout) > 0 || usecs > READ_OUTPUT_DELAY_MAX)
4772 usecs = READ_OUTPUT_DELAY_MAX;
4773 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4774 {
4775 proc = chan_process[channel];
4776 if (NILP (proc))
4777 continue;
4778 /* Find minimum non-zero read_output_delay among the
4779 processes with non-zero read_output_skip. */
4780 if (XPROCESS (proc)->read_output_delay > 0)
4781 {
4782 check_delay--;
4783 if (!XPROCESS (proc)->read_output_skip)
4784 continue;
4785 FD_CLR (channel, &Available);
4786 XPROCESS (proc)->read_output_skip = 0;
4787 if (XPROCESS (proc)->read_output_delay < usecs)
4788 usecs = XPROCESS (proc)->read_output_delay;
4789 }
4790 }
4791 EMACS_SET_SECS_USECS (timeout, 0, usecs);
4792 process_output_skip = 0;
4793 }
4794 #endif
4795 #if defined (USE_GTK) || defined (HAVE_GCONF)
4796 nfds = xg_select
4797 #elif defined (HAVE_NS)
4798 nfds = ns_select
4799 #else
4800 nfds = select
4801 #endif
4802 (max (max_process_desc, max_input_desc) + 1,
4803 &Available,
4804 (check_write ? &Writeok : (SELECT_TYPE *)0),
4805 (SELECT_TYPE *)0, &timeout);
4806 }
4807
4808 xerrno = errno;
4809
4810 /* Make C-g and alarm signals set flags again */
4811 clear_waiting_for_input ();
4812
4813 /* If we woke up due to SIGWINCH, actually change size now. */
4814 do_pending_window_change (0);
4815
4816 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
4817 /* We wanted the full specified time, so return now. */
4818 break;
4819 if (nfds < 0)
4820 {
4821 if (xerrno == EINTR)
4822 no_avail = 1;
4823 else if (xerrno == EBADF)
4824 {
4825 #ifdef AIX
4826 /* AIX doesn't handle PTY closure the same way BSD does. On AIX,
4827 the child's closure of the pts gives the parent a SIGHUP, and
4828 the ptc file descriptor is automatically closed,
4829 yielding EBADF here or at select() call above.
4830 So, SIGHUP is ignored (see def of PTY_TTY_NAME_SPRINTF
4831 in m/ibmrt-aix.h), and here we just ignore the select error.
4832 Cleanup occurs c/o status_notify after SIGCLD. */
4833 no_avail = 1; /* Cannot depend on values returned */
4834 #else
4835 abort ();
4836 #endif
4837 }
4838 else
4839 error ("select error: %s", emacs_strerror (xerrno));
4840 }
4841
4842 if (no_avail)
4843 {
4844 FD_ZERO (&Available);
4845 check_write = 0;
4846 }
4847
4848 #if 0 /* When polling is used, interrupt_input is 0,
4849 so get_input_pending should read the input.
4850 So this should not be needed. */
4851 /* If we are using polling for input,
4852 and we see input available, make it get read now.
4853 Otherwise it might not actually get read for a second.
4854 And on hpux, since we turn off polling in wait_reading_process_output,
4855 it might never get read at all if we don't spend much time
4856 outside of wait_reading_process_output. */
4857 if (read_kbd && interrupt_input
4858 && keyboard_bit_set (&Available)
4859 && input_polling_used ())
4860 kill (getpid (), SIGALRM);
4861 #endif
4862
4863 /* Check for keyboard input */
4864 /* If there is any, return immediately
4865 to give it higher priority than subprocesses */
4866
4867 if (read_kbd != 0)
4868 {
4869 int old_timers_run = timers_run;
4870 struct buffer *old_buffer = current_buffer;
4871 Lisp_Object old_window = selected_window;
4872 int leave = 0;
4873
4874 if (detect_input_pending_run_timers (do_display))
4875 {
4876 swallow_events (do_display);
4877 if (detect_input_pending_run_timers (do_display))
4878 leave = 1;
4879 }
4880
4881 /* If a timer has run, this might have changed buffers
4882 an alike. Make read_key_sequence aware of that. */
4883 if (timers_run != old_timers_run
4884 && waiting_for_user_input_p == -1
4885 && (old_buffer != current_buffer
4886 || !EQ (old_window, selected_window)))
4887 record_asynch_buffer_change ();
4888
4889 if (leave)
4890 break;
4891 }
4892
4893 /* If there is unread keyboard input, also return. */
4894 if (read_kbd != 0
4895 && requeued_events_pending_p ())
4896 break;
4897
4898 /* If we are not checking for keyboard input now,
4899 do process events (but don't run any timers).
4900 This is so that X events will be processed.
4901 Otherwise they may have to wait until polling takes place.
4902 That would causes delays in pasting selections, for example.
4903
4904 (We used to do this only if wait_for_cell.) */
4905 if (read_kbd == 0 && detect_input_pending ())
4906 {
4907 swallow_events (do_display);
4908 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4909 if (detect_input_pending ())
4910 break;
4911 #endif
4912 }
4913
4914 /* Exit now if the cell we're waiting for became non-nil. */
4915 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4916 break;
4917
4918 #ifdef SIGIO
4919 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4920 go read it. This can happen with X on BSD after logging out.
4921 In that case, there really is no input and no SIGIO,
4922 but select says there is input. */
4923
4924 if (read_kbd && interrupt_input
4925 && keyboard_bit_set (&Available) && ! noninteractive)
4926 kill (getpid (), SIGIO);
4927 #endif
4928
4929 if (! wait_proc)
4930 got_some_input |= nfds > 0;
4931
4932 /* If checking input just got us a size-change event from X,
4933 obey it now if we should. */
4934 if (read_kbd || ! NILP (wait_for_cell))
4935 do_pending_window_change (0);
4936
4937 /* Check for data from a process. */
4938 if (no_avail || nfds == 0)
4939 continue;
4940
4941 for (channel = 0; channel <= max_input_desc; ++channel)
4942 {
4943 struct fd_callback_data *d = &fd_callback_info[channel];
4944 if (FD_ISSET (channel, &Available)
4945 && d->func != 0
4946 && (d->condition & FOR_READ) != 0)
4947 d->func (channel, d->data, 1);
4948 if (FD_ISSET (channel, &write_mask)
4949 && d->func != 0
4950 && (d->condition & FOR_WRITE) != 0)
4951 d->func (channel, d->data, 0);
4952 }
4953
4954 /* Really FIRST_PROC_DESC should be 0 on Unix,
4955 but this is safer in the short run. */
4956 for (channel = 0; channel <= max_process_desc; channel++)
4957 {
4958 if (FD_ISSET (channel, &Available)
4959 && FD_ISSET (channel, &non_keyboard_wait_mask)
4960 && !FD_ISSET (channel, &non_process_wait_mask))
4961 {
4962 int nread;
4963
4964 /* If waiting for this channel, arrange to return as
4965 soon as no more input to be processed. No more
4966 waiting. */
4967 if (wait_channel == channel)
4968 {
4969 wait_channel = -1;
4970 time_limit = -1;
4971 got_some_input = 1;
4972 }
4973 proc = chan_process[channel];
4974 if (NILP (proc))
4975 continue;
4976
4977 /* If this is a server stream socket, accept connection. */
4978 if (EQ (XPROCESS (proc)->status, Qlisten))
4979 {
4980 server_accept_connection (proc, channel);
4981 continue;
4982 }
4983
4984 /* Read data from the process, starting with our
4985 buffered-ahead character if we have one. */
4986
4987 nread = read_process_output (proc, channel);
4988 if (nread > 0)
4989 {
4990 /* Since read_process_output can run a filter,
4991 which can call accept-process-output,
4992 don't try to read from any other processes
4993 before doing the select again. */
4994 FD_ZERO (&Available);
4995
4996 if (do_display)
4997 redisplay_preserve_echo_area (12);
4998 }
4999 #ifdef EWOULDBLOCK
5000 else if (nread == -1 && errno == EWOULDBLOCK)
5001 ;
5002 #endif
5003 /* ISC 4.1 defines both EWOULDBLOCK and O_NONBLOCK,
5004 and Emacs uses O_NONBLOCK, so what we get is EAGAIN. */
5005 #ifdef O_NONBLOCK
5006 else if (nread == -1 && errno == EAGAIN)
5007 ;
5008 #else
5009 #ifdef O_NDELAY
5010 else if (nread == -1 && errno == EAGAIN)
5011 ;
5012 /* Note that we cannot distinguish between no input
5013 available now and a closed pipe.
5014 With luck, a closed pipe will be accompanied by
5015 subprocess termination and SIGCHLD. */
5016 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
5017 ;
5018 #endif /* O_NDELAY */
5019 #endif /* O_NONBLOCK */
5020 #ifdef HAVE_PTYS
5021 /* On some OSs with ptys, when the process on one end of
5022 a pty exits, the other end gets an error reading with
5023 errno = EIO instead of getting an EOF (0 bytes read).
5024 Therefore, if we get an error reading and errno =
5025 EIO, just continue, because the child process has
5026 exited and should clean itself up soon (e.g. when we
5027 get a SIGCHLD).
5028
5029 However, it has been known to happen that the SIGCHLD
5030 got lost. So raise the signal again just in case.
5031 It can't hurt. */
5032 else if (nread == -1 && errno == EIO)
5033 {
5034 /* Clear the descriptor now, so we only raise the
5035 signal once. Don't do this if `process' is only
5036 a pty. */
5037 if (XPROCESS (proc)->pid != -2)
5038 {
5039 FD_CLR (channel, &input_wait_mask);
5040 FD_CLR (channel, &non_keyboard_wait_mask);
5041
5042 kill (getpid (), SIGCHLD);
5043 }
5044 }
5045 #endif /* HAVE_PTYS */
5046 /* If we can detect process termination, don't consider the process
5047 gone just because its pipe is closed. */
5048 #ifdef SIGCHLD
5049 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
5050 ;
5051 #endif
5052 else
5053 {
5054 /* Preserve status of processes already terminated. */
5055 XPROCESS (proc)->tick = ++process_tick;
5056 deactivate_process (proc);
5057 if (XPROCESS (proc)->raw_status_new)
5058 update_status (XPROCESS (proc));
5059 if (EQ (XPROCESS (proc)->status, Qrun))
5060 XPROCESS (proc)->status
5061 = Fcons (Qexit, Fcons (make_number (256), Qnil));
5062 }
5063 }
5064 #ifdef NON_BLOCKING_CONNECT
5065 if (FD_ISSET (channel, &Writeok)
5066 && FD_ISSET (channel, &connect_wait_mask))
5067 {
5068 struct Lisp_Process *p;
5069
5070 FD_CLR (channel, &connect_wait_mask);
5071 FD_CLR (channel, &write_mask);
5072 if (--num_pending_connects < 0)
5073 abort ();
5074
5075 proc = chan_process[channel];
5076 if (NILP (proc))
5077 continue;
5078
5079 p = XPROCESS (proc);
5080
5081 #ifdef GNU_LINUX
5082 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5083 So only use it on systems where it is known to work. */
5084 {
5085 int xlen = sizeof (xerrno);
5086 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5087 xerrno = errno;
5088 }
5089 #else
5090 {
5091 struct sockaddr pname;
5092 int pnamelen = sizeof (pname);
5093
5094 /* If connection failed, getpeername will fail. */
5095 xerrno = 0;
5096 if (getpeername (channel, &pname, &pnamelen) < 0)
5097 {
5098 /* Obtain connect failure code through error slippage. */
5099 char dummy;
5100 xerrno = errno;
5101 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
5102 xerrno = errno;
5103 }
5104 }
5105 #endif
5106 if (xerrno)
5107 {
5108 p->tick = ++process_tick;
5109 p->status = Fcons (Qfailed, Fcons (make_number (xerrno), Qnil));
5110 deactivate_process (proc);
5111 }
5112 else
5113 {
5114 p->status = Qrun;
5115 /* Execute the sentinel here. If we had relied on
5116 status_notify to do it later, it will read input
5117 from the process before calling the sentinel. */
5118 exec_sentinel (proc, build_string ("open\n"));
5119 if (!EQ (p->filter, Qt) && !EQ (p->command, Qt))
5120 {
5121 FD_SET (p->infd, &input_wait_mask);
5122 FD_SET (p->infd, &non_keyboard_wait_mask);
5123 }
5124 }
5125 }
5126 #endif /* NON_BLOCKING_CONNECT */
5127 } /* end for each file descriptor */
5128 } /* end while exit conditions not met */
5129
5130 unbind_to (count, Qnil);
5131
5132 /* If calling from keyboard input, do not quit
5133 since we want to return C-g as an input character.
5134 Otherwise, do pending quit if requested. */
5135 if (read_kbd >= 0)
5136 {
5137 /* Prevent input_pending from remaining set if we quit. */
5138 clear_input_pending ();
5139 QUIT;
5140 }
5141
5142 return got_some_input;
5143 }
5144 \f
5145 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5146
5147 static Lisp_Object
5148 read_process_output_call (Lisp_Object fun_and_args)
5149 {
5150 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5151 }
5152
5153 static Lisp_Object
5154 read_process_output_error_handler (Lisp_Object error)
5155 {
5156 cmd_error_internal (error, "error in process filter: ");
5157 Vinhibit_quit = Qt;
5158 update_echo_area ();
5159 Fsleep_for (make_number (2), Qnil);
5160 return Qt;
5161 }
5162
5163 /* Read pending output from the process channel,
5164 starting with our buffered-ahead character if we have one.
5165 Yield number of decoded characters read.
5166
5167 This function reads at most 4096 characters.
5168 If you want to read all available subprocess output,
5169 you must call it repeatedly until it returns zero.
5170
5171 The characters read are decoded according to PROC's coding-system
5172 for decoding. */
5173
5174 static int
5175 read_process_output (Lisp_Object proc, register int channel)
5176 {
5177 register int nbytes;
5178 char *chars;
5179 register Lisp_Object outstream;
5180 register struct Lisp_Process *p = XPROCESS (proc);
5181 register EMACS_INT opoint;
5182 struct coding_system *coding = proc_decode_coding_system[channel];
5183 int carryover = p->decoding_carryover;
5184 int readmax = 4096;
5185 int count = SPECPDL_INDEX ();
5186 Lisp_Object odeactivate;
5187
5188 chars = (char *) alloca (carryover + readmax);
5189 if (carryover)
5190 /* See the comment above. */
5191 memcpy (chars, SDATA (p->decoding_buf), carryover);
5192
5193 #ifdef DATAGRAM_SOCKETS
5194 /* We have a working select, so proc_buffered_char is always -1. */
5195 if (DATAGRAM_CHAN_P (channel))
5196 {
5197 int len = datagram_address[channel].len;
5198 nbytes = recvfrom (channel, chars + carryover, readmax,
5199 0, datagram_address[channel].sa, &len);
5200 }
5201 else
5202 #endif
5203 if (proc_buffered_char[channel] < 0)
5204 {
5205 #ifdef HAVE_GNUTLS
5206 if (NETCONN_P(proc) && GNUTLS_PROCESS_USABLE (proc))
5207 nbytes = emacs_gnutls_read (channel, XPROCESS (proc)->gnutls_state,
5208 chars + carryover, readmax);
5209 else
5210 #endif
5211 nbytes = emacs_read (channel, chars + carryover, readmax);
5212 #ifdef ADAPTIVE_READ_BUFFERING
5213 if (nbytes > 0 && p->adaptive_read_buffering)
5214 {
5215 int delay = p->read_output_delay;
5216 if (nbytes < 256)
5217 {
5218 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5219 {
5220 if (delay == 0)
5221 process_output_delay_count++;
5222 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5223 }
5224 }
5225 else if (delay > 0 && (nbytes == readmax))
5226 {
5227 delay -= READ_OUTPUT_DELAY_INCREMENT;
5228 if (delay == 0)
5229 process_output_delay_count--;
5230 }
5231 p->read_output_delay = delay;
5232 if (delay)
5233 {
5234 p->read_output_skip = 1;
5235 process_output_skip = 1;
5236 }
5237 }
5238 #endif
5239 }
5240 else
5241 {
5242 chars[carryover] = proc_buffered_char[channel];
5243 proc_buffered_char[channel] = -1;
5244 #ifdef HAVE_GNUTLS
5245 if (NETCONN_P(proc) && GNUTLS_PROCESS_USABLE (proc))
5246 nbytes = emacs_gnutls_read (channel, XPROCESS (proc)->gnutls_state,
5247 chars + carryover + 1, readmax - 1);
5248 else
5249 #endif
5250 nbytes = emacs_read (channel, chars + carryover + 1, readmax - 1);
5251 if (nbytes < 0)
5252 nbytes = 1;
5253 else
5254 nbytes = nbytes + 1;
5255 }
5256
5257 p->decoding_carryover = 0;
5258
5259 /* At this point, NBYTES holds number of bytes just received
5260 (including the one in proc_buffered_char[channel]). */
5261 if (nbytes <= 0)
5262 {
5263 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5264 return nbytes;
5265 coding->mode |= CODING_MODE_LAST_BLOCK;
5266 }
5267
5268 /* Now set NBYTES how many bytes we must decode. */
5269 nbytes += carryover;
5270
5271 odeactivate = Vdeactivate_mark;
5272 /* There's no good reason to let process filters change the current
5273 buffer, and many callers of accept-process-output, sit-for, and
5274 friends don't expect current-buffer to be changed from under them. */
5275 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
5276
5277 /* Read and dispose of the process output. */
5278 outstream = p->filter;
5279 if (!NILP (outstream))
5280 {
5281 Lisp_Object obuffer, okeymap;
5282 Lisp_Object text;
5283 int outer_running_asynch_code = running_asynch_code;
5284 int waiting = waiting_for_user_input_p;
5285
5286 /* No need to gcpro these, because all we do with them later
5287 is test them for EQness, and none of them should be a string. */
5288 XSETBUFFER (obuffer, current_buffer);
5289 okeymap = current_buffer->keymap;
5290
5291 /* We inhibit quit here instead of just catching it so that
5292 hitting ^G when a filter happens to be running won't screw
5293 it up. */
5294 specbind (Qinhibit_quit, Qt);
5295 specbind (Qlast_nonmenu_event, Qt);
5296
5297 /* In case we get recursively called,
5298 and we already saved the match data nonrecursively,
5299 save the same match data in safely recursive fashion. */
5300 if (outer_running_asynch_code)
5301 {
5302 Lisp_Object tem;
5303 /* Don't clobber the CURRENT match data, either! */
5304 tem = Fmatch_data (Qnil, Qnil, Qnil);
5305 restore_search_regs ();
5306 record_unwind_save_match_data ();
5307 Fset_match_data (tem, Qt);
5308 }
5309
5310 /* For speed, if a search happens within this code,
5311 save the match data in a special nonrecursive fashion. */
5312 running_asynch_code = 1;
5313
5314 decode_coding_c_string (coding, chars, nbytes, Qt);
5315 text = coding->dst_object;
5316 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5317 /* A new coding system might be found. */
5318 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5319 {
5320 p->decode_coding_system = Vlast_coding_system_used;
5321
5322 /* Don't call setup_coding_system for
5323 proc_decode_coding_system[channel] here. It is done in
5324 detect_coding called via decode_coding above. */
5325
5326 /* If a coding system for encoding is not yet decided, we set
5327 it as the same as coding-system for decoding.
5328
5329 But, before doing that we must check if
5330 proc_encode_coding_system[p->outfd] surely points to a
5331 valid memory because p->outfd will be changed once EOF is
5332 sent to the process. */
5333 if (NILP (p->encode_coding_system)
5334 && proc_encode_coding_system[p->outfd])
5335 {
5336 p->encode_coding_system
5337 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5338 setup_coding_system (p->encode_coding_system,
5339 proc_encode_coding_system[p->outfd]);
5340 }
5341 }
5342
5343 if (coding->carryover_bytes > 0)
5344 {
5345 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5346 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5347 memcpy (SDATA (p->decoding_buf), coding->carryover,
5348 coding->carryover_bytes);
5349 p->decoding_carryover = coding->carryover_bytes;
5350 }
5351 if (SBYTES (text) > 0)
5352 internal_condition_case_1 (read_process_output_call,
5353 Fcons (outstream,
5354 Fcons (proc, Fcons (text, Qnil))),
5355 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5356 read_process_output_error_handler);
5357
5358 /* If we saved the match data nonrecursively, restore it now. */
5359 restore_search_regs ();
5360 running_asynch_code = outer_running_asynch_code;
5361
5362 /* Restore waiting_for_user_input_p as it was
5363 when we were called, in case the filter clobbered it. */
5364 waiting_for_user_input_p = waiting;
5365
5366 #if 0 /* Call record_asynch_buffer_change unconditionally,
5367 because we might have changed minor modes or other things
5368 that affect key bindings. */
5369 if (! EQ (Fcurrent_buffer (), obuffer)
5370 || ! EQ (current_buffer->keymap, okeymap))
5371 #endif
5372 /* But do it only if the caller is actually going to read events.
5373 Otherwise there's no need to make him wake up, and it could
5374 cause trouble (for example it would make sit_for return). */
5375 if (waiting_for_user_input_p == -1)
5376 record_asynch_buffer_change ();
5377 }
5378
5379 /* If no filter, write into buffer if it isn't dead. */
5380 else if (!NILP (p->buffer) && !NILP (XBUFFER (p->buffer)->name))
5381 {
5382 Lisp_Object old_read_only;
5383 EMACS_INT old_begv, old_zv;
5384 EMACS_INT old_begv_byte, old_zv_byte;
5385 EMACS_INT before, before_byte;
5386 EMACS_INT opoint_byte;
5387 Lisp_Object text;
5388 struct buffer *b;
5389
5390 Fset_buffer (p->buffer);
5391 opoint = PT;
5392 opoint_byte = PT_BYTE;
5393 old_read_only = current_buffer->read_only;
5394 old_begv = BEGV;
5395 old_zv = ZV;
5396 old_begv_byte = BEGV_BYTE;
5397 old_zv_byte = ZV_BYTE;
5398
5399 current_buffer->read_only = Qnil;
5400
5401 /* Insert new output into buffer
5402 at the current end-of-output marker,
5403 thus preserving logical ordering of input and output. */
5404 if (XMARKER (p->mark)->buffer)
5405 SET_PT_BOTH (clip_to_bounds (BEGV, marker_position (p->mark), ZV),
5406 clip_to_bounds (BEGV_BYTE, marker_byte_position (p->mark),
5407 ZV_BYTE));
5408 else
5409 SET_PT_BOTH (ZV, ZV_BYTE);
5410 before = PT;
5411 before_byte = PT_BYTE;
5412
5413 /* If the output marker is outside of the visible region, save
5414 the restriction and widen. */
5415 if (! (BEGV <= PT && PT <= ZV))
5416 Fwiden ();
5417
5418 decode_coding_c_string (coding, chars, nbytes, Qt);
5419 text = coding->dst_object;
5420 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5421 /* A new coding system might be found. See the comment in the
5422 similar code in the previous `if' block. */
5423 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5424 {
5425 p->decode_coding_system = Vlast_coding_system_used;
5426 if (NILP (p->encode_coding_system)
5427 && proc_encode_coding_system[p->outfd])
5428 {
5429 p->encode_coding_system
5430 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5431 setup_coding_system (p->encode_coding_system,
5432 proc_encode_coding_system[p->outfd]);
5433 }
5434 }
5435 if (coding->carryover_bytes > 0)
5436 {
5437 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5438 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5439 memcpy (SDATA (p->decoding_buf), coding->carryover,
5440 coding->carryover_bytes);
5441 p->decoding_carryover = coding->carryover_bytes;
5442 }
5443 /* Adjust the multibyteness of TEXT to that of the buffer. */
5444 if (NILP (current_buffer->enable_multibyte_characters)
5445 != ! STRING_MULTIBYTE (text))
5446 text = (STRING_MULTIBYTE (text)
5447 ? Fstring_as_unibyte (text)
5448 : Fstring_to_multibyte (text));
5449 /* Insert before markers in case we are inserting where
5450 the buffer's mark is, and the user's next command is Meta-y. */
5451 insert_from_string_before_markers (text, 0, 0,
5452 SCHARS (text), SBYTES (text), 0);
5453
5454 /* Make sure the process marker's position is valid when the
5455 process buffer is changed in the signal_after_change above.
5456 W3 is known to do that. */
5457 if (BUFFERP (p->buffer)
5458 && (b = XBUFFER (p->buffer), b != current_buffer))
5459 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5460 else
5461 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5462
5463 update_mode_lines++;
5464
5465 /* Make sure opoint and the old restrictions
5466 float ahead of any new text just as point would. */
5467 if (opoint >= before)
5468 {
5469 opoint += PT - before;
5470 opoint_byte += PT_BYTE - before_byte;
5471 }
5472 if (old_begv > before)
5473 {
5474 old_begv += PT - before;
5475 old_begv_byte += PT_BYTE - before_byte;
5476 }
5477 if (old_zv >= before)
5478 {
5479 old_zv += PT - before;
5480 old_zv_byte += PT_BYTE - before_byte;
5481 }
5482
5483 /* If the restriction isn't what it should be, set it. */
5484 if (old_begv != BEGV || old_zv != ZV)
5485 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5486
5487
5488 current_buffer->read_only = old_read_only;
5489 SET_PT_BOTH (opoint, opoint_byte);
5490 }
5491 /* Handling the process output should not deactivate the mark. */
5492 Vdeactivate_mark = odeactivate;
5493
5494 unbind_to (count, Qnil);
5495 return nbytes;
5496 }
5497 \f
5498 /* Sending data to subprocess */
5499
5500 jmp_buf send_process_frame;
5501 Lisp_Object process_sent_to;
5502
5503 SIGTYPE
5504 send_process_trap (int ignore)
5505 {
5506 SIGNAL_THREAD_CHECK (SIGPIPE);
5507 sigunblock (sigmask (SIGPIPE));
5508 longjmp (send_process_frame, 1);
5509 }
5510
5511 /* Send some data to process PROC.
5512 BUF is the beginning of the data; LEN is the number of characters.
5513 OBJECT is the Lisp object that the data comes from. If OBJECT is
5514 nil or t, it means that the data comes from C string.
5515
5516 If OBJECT is not nil, the data is encoded by PROC's coding-system
5517 for encoding before it is sent.
5518
5519 This function can evaluate Lisp code and can garbage collect. */
5520
5521 static void
5522 send_process (volatile Lisp_Object proc, const unsigned char *volatile buf,
5523 volatile EMACS_INT len, volatile Lisp_Object object)
5524 {
5525 /* Use volatile to protect variables from being clobbered by longjmp. */
5526 struct Lisp_Process *p = XPROCESS (proc);
5527 EMACS_INT rv;
5528 struct coding_system *coding;
5529 struct gcpro gcpro1;
5530 SIGTYPE (*volatile old_sigpipe) (int);
5531
5532 GCPRO1 (object);
5533
5534 if (p->raw_status_new)
5535 update_status (p);
5536 if (! EQ (p->status, Qrun))
5537 error ("Process %s not running", SDATA (p->name));
5538 if (p->outfd < 0)
5539 error ("Output file descriptor of %s is closed", SDATA (p->name));
5540
5541 coding = proc_encode_coding_system[p->outfd];
5542 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5543
5544 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5545 || (BUFFERP (object)
5546 && !NILP (XBUFFER (object)->enable_multibyte_characters))
5547 || EQ (object, Qt))
5548 {
5549 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5550 /* The coding system for encoding was changed to raw-text
5551 because we sent a unibyte text previously. Now we are
5552 sending a multibyte text, thus we must encode it by the
5553 original coding system specified for the current process. */
5554 setup_coding_system (p->encode_coding_system, coding);
5555 coding->src_multibyte = 1;
5556 }
5557 else
5558 {
5559 /* For sending a unibyte text, character code conversion should
5560 not take place but EOL conversion should. So, setup raw-text
5561 or one of the subsidiary if we have not yet done it. */
5562 if (CODING_REQUIRE_ENCODING (coding))
5563 {
5564 if (CODING_REQUIRE_FLUSHING (coding))
5565 {
5566 /* But, before changing the coding, we must flush out data. */
5567 coding->mode |= CODING_MODE_LAST_BLOCK;
5568 send_process (proc, "", 0, Qt);
5569 coding->mode &= CODING_MODE_LAST_BLOCK;
5570 }
5571 setup_coding_system (raw_text_coding_system
5572 (Vlast_coding_system_used),
5573 coding);
5574 coding->src_multibyte = 0;
5575 }
5576 }
5577 coding->dst_multibyte = 0;
5578
5579 if (CODING_REQUIRE_ENCODING (coding))
5580 {
5581 coding->dst_object = Qt;
5582 if (BUFFERP (object))
5583 {
5584 EMACS_INT from_byte, from, to;
5585 EMACS_INT save_pt, save_pt_byte;
5586 struct buffer *cur = current_buffer;
5587
5588 set_buffer_internal (XBUFFER (object));
5589 save_pt = PT, save_pt_byte = PT_BYTE;
5590
5591 from_byte = PTR_BYTE_POS (buf);
5592 from = BYTE_TO_CHAR (from_byte);
5593 to = BYTE_TO_CHAR (from_byte + len);
5594 TEMP_SET_PT_BOTH (from, from_byte);
5595 encode_coding_object (coding, object, from, from_byte,
5596 to, from_byte + len, Qt);
5597 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5598 set_buffer_internal (cur);
5599 }
5600 else if (STRINGP (object))
5601 {
5602 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5603 SBYTES (object), Qt);
5604 }
5605 else
5606 {
5607 coding->dst_object = make_unibyte_string (buf, len);
5608 coding->produced = len;
5609 }
5610
5611 len = coding->produced;
5612 object = coding->dst_object;
5613 buf = SDATA (object);
5614 }
5615
5616 if (pty_max_bytes == 0)
5617 {
5618 #if defined (HAVE_FPATHCONF) && defined (_PC_MAX_CANON)
5619 pty_max_bytes = fpathconf (p->outfd, _PC_MAX_CANON);
5620 if (pty_max_bytes < 0)
5621 pty_max_bytes = 250;
5622 #else
5623 pty_max_bytes = 250;
5624 #endif
5625 /* Deduct one, to leave space for the eof. */
5626 pty_max_bytes--;
5627 }
5628
5629 /* 2000-09-21: Emacs 20.7, sparc-sun-solaris-2.6, GCC 2.95.2,
5630 CFLAGS="-g -O": The value of the parameter `proc' is clobbered
5631 when returning with longjmp despite being declared volatile. */
5632 if (!setjmp (send_process_frame))
5633 {
5634 process_sent_to = proc;
5635 while (len > 0)
5636 {
5637 EMACS_INT this = len;
5638
5639 /* Send this batch, using one or more write calls. */
5640 while (this > 0)
5641 {
5642 int outfd = p->outfd;
5643 old_sigpipe = (SIGTYPE (*) (int)) signal (SIGPIPE, send_process_trap);
5644 #ifdef DATAGRAM_SOCKETS
5645 if (DATAGRAM_CHAN_P (outfd))
5646 {
5647 rv = sendto (outfd, (char *) buf, this,
5648 0, datagram_address[outfd].sa,
5649 datagram_address[outfd].len);
5650 if (rv < 0 && errno == EMSGSIZE)
5651 {
5652 signal (SIGPIPE, old_sigpipe);
5653 report_file_error ("sending datagram",
5654 Fcons (proc, Qnil));
5655 }
5656 }
5657 else
5658 #endif
5659 {
5660 #ifdef HAVE_GNUTLS
5661 if (NETCONN_P(proc) && GNUTLS_PROCESS_USABLE (proc))
5662 rv = emacs_gnutls_write (outfd,
5663 XPROCESS (proc)->gnutls_state,
5664 (char *) buf, this);
5665 else
5666 #endif
5667 rv = emacs_write (outfd, (char *) buf, this);
5668 #ifdef ADAPTIVE_READ_BUFFERING
5669 if (p->read_output_delay > 0
5670 && p->adaptive_read_buffering == 1)
5671 {
5672 p->read_output_delay = 0;
5673 process_output_delay_count--;
5674 p->read_output_skip = 0;
5675 }
5676 #endif
5677 }
5678 signal (SIGPIPE, old_sigpipe);
5679
5680 if (rv < 0)
5681 {
5682 if (0
5683 #ifdef EWOULDBLOCK
5684 || errno == EWOULDBLOCK
5685 #endif
5686 #ifdef EAGAIN
5687 || errno == EAGAIN
5688 #endif
5689 )
5690 /* Buffer is full. Wait, accepting input;
5691 that may allow the program
5692 to finish doing output and read more. */
5693 {
5694 int offset = 0;
5695
5696 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5697 /* A gross hack to work around a bug in FreeBSD.
5698 In the following sequence, read(2) returns
5699 bogus data:
5700
5701 write(2) 1022 bytes
5702 write(2) 954 bytes, get EAGAIN
5703 read(2) 1024 bytes in process_read_output
5704 read(2) 11 bytes in process_read_output
5705
5706 That is, read(2) returns more bytes than have
5707 ever been written successfully. The 1033 bytes
5708 read are the 1022 bytes written successfully
5709 after processing (for example with CRs added if
5710 the terminal is set up that way which it is
5711 here). The same bytes will be seen again in a
5712 later read(2), without the CRs. */
5713
5714 if (errno == EAGAIN)
5715 {
5716 int flags = FWRITE;
5717 ioctl (p->outfd, TIOCFLUSH, &flags);
5718 }
5719 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5720
5721 /* Running filters might relocate buffers or strings.
5722 Arrange to relocate BUF. */
5723 if (BUFFERP (object))
5724 offset = BUF_PTR_BYTE_POS (XBUFFER (object), buf);
5725 else if (STRINGP (object))
5726 offset = buf - SDATA (object);
5727
5728 #ifdef EMACS_HAS_USECS
5729 wait_reading_process_output (0, 20000, 0, 0, Qnil, NULL, 0);
5730 #else
5731 wait_reading_process_output (1, 0, 0, 0, Qnil, NULL, 0);
5732 #endif
5733
5734 if (BUFFERP (object))
5735 buf = BUF_BYTE_ADDRESS (XBUFFER (object), offset);
5736 else if (STRINGP (object))
5737 buf = offset + SDATA (object);
5738
5739 rv = 0;
5740 }
5741 else
5742 /* This is a real error. */
5743 report_file_error ("writing to process", Fcons (proc, Qnil));
5744 }
5745 buf += rv;
5746 len -= rv;
5747 this -= rv;
5748 }
5749 }
5750 }
5751 else
5752 {
5753 signal (SIGPIPE, old_sigpipe);
5754 proc = process_sent_to;
5755 p = XPROCESS (proc);
5756 p->raw_status_new = 0;
5757 p->status = Fcons (Qexit, Fcons (make_number (256), Qnil));
5758 p->tick = ++process_tick;
5759 deactivate_process (proc);
5760 error ("SIGPIPE raised on process %s; closed it", SDATA (p->name));
5761 }
5762
5763 UNGCPRO;
5764 }
5765
5766 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5767 3, 3, 0,
5768 doc: /* Send current contents of region as input to PROCESS.
5769 PROCESS may be a process, a buffer, the name of a process or buffer, or
5770 nil, indicating the current buffer's process.
5771 Called from program, takes three arguments, PROCESS, START and END.
5772 If the region is more than 500 characters long,
5773 it is sent in several bunches. This may happen even for shorter regions.
5774 Output from processes can arrive in between bunches. */)
5775 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
5776 {
5777 Lisp_Object proc;
5778 EMACS_INT start1, end1;
5779
5780 proc = get_process (process);
5781 validate_region (&start, &end);
5782
5783 if (XINT (start) < GPT && XINT (end) > GPT)
5784 move_gap (XINT (start));
5785
5786 start1 = CHAR_TO_BYTE (XINT (start));
5787 end1 = CHAR_TO_BYTE (XINT (end));
5788 send_process (proc, BYTE_POS_ADDR (start1), end1 - start1,
5789 Fcurrent_buffer ());
5790
5791 return Qnil;
5792 }
5793
5794 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5795 2, 2, 0,
5796 doc: /* Send PROCESS the contents of STRING as input.
5797 PROCESS may be a process, a buffer, the name of a process or buffer, or
5798 nil, indicating the current buffer's process.
5799 If STRING is more than 500 characters long,
5800 it is sent in several bunches. This may happen even for shorter strings.
5801 Output from processes can arrive in between bunches. */)
5802 (Lisp_Object process, Lisp_Object string)
5803 {
5804 Lisp_Object proc;
5805 CHECK_STRING (string);
5806 proc = get_process (process);
5807 send_process (proc, SDATA (string),
5808 SBYTES (string), string);
5809 return Qnil;
5810 }
5811 \f
5812 /* Return the foreground process group for the tty/pty that
5813 the process P uses. */
5814 static int
5815 emacs_get_tty_pgrp (struct Lisp_Process *p)
5816 {
5817 int gid = -1;
5818
5819 #ifdef TIOCGPGRP
5820 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5821 {
5822 int fd;
5823 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5824 master side. Try the slave side. */
5825 fd = emacs_open (SDATA (p->tty_name), O_RDONLY, 0);
5826
5827 if (fd != -1)
5828 {
5829 ioctl (fd, TIOCGPGRP, &gid);
5830 emacs_close (fd);
5831 }
5832 }
5833 #endif /* defined (TIOCGPGRP ) */
5834
5835 return gid;
5836 }
5837
5838 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5839 Sprocess_running_child_p, 0, 1, 0,
5840 doc: /* Return t if PROCESS has given the terminal to a child.
5841 If the operating system does not make it possible to find out,
5842 return t unconditionally. */)
5843 (Lisp_Object process)
5844 {
5845 /* Initialize in case ioctl doesn't exist or gives an error,
5846 in a way that will cause returning t. */
5847 int gid;
5848 Lisp_Object proc;
5849 struct Lisp_Process *p;
5850
5851 proc = get_process (process);
5852 p = XPROCESS (proc);
5853
5854 if (!EQ (p->type, Qreal))
5855 error ("Process %s is not a subprocess",
5856 SDATA (p->name));
5857 if (p->infd < 0)
5858 error ("Process %s is not active",
5859 SDATA (p->name));
5860
5861 gid = emacs_get_tty_pgrp (p);
5862
5863 if (gid == p->pid)
5864 return Qnil;
5865 return Qt;
5866 }
5867 \f
5868 /* send a signal number SIGNO to PROCESS.
5869 If CURRENT_GROUP is t, that means send to the process group
5870 that currently owns the terminal being used to communicate with PROCESS.
5871 This is used for various commands in shell mode.
5872 If CURRENT_GROUP is lambda, that means send to the process group
5873 that currently owns the terminal, but only if it is NOT the shell itself.
5874
5875 If NOMSG is zero, insert signal-announcements into process's buffers
5876 right away.
5877
5878 If we can, we try to signal PROCESS by sending control characters
5879 down the pty. This allows us to signal inferiors who have changed
5880 their uid, for which killpg would return an EPERM error. */
5881
5882 static void
5883 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
5884 int nomsg)
5885 {
5886 Lisp_Object proc;
5887 register struct Lisp_Process *p;
5888 int gid;
5889 int no_pgrp = 0;
5890
5891 proc = get_process (process);
5892 p = XPROCESS (proc);
5893
5894 if (!EQ (p->type, Qreal))
5895 error ("Process %s is not a subprocess",
5896 SDATA (p->name));
5897 if (p->infd < 0)
5898 error ("Process %s is not active",
5899 SDATA (p->name));
5900
5901 if (!p->pty_flag)
5902 current_group = Qnil;
5903
5904 /* If we are using pgrps, get a pgrp number and make it negative. */
5905 if (NILP (current_group))
5906 /* Send the signal to the shell's process group. */
5907 gid = p->pid;
5908 else
5909 {
5910 #ifdef SIGNALS_VIA_CHARACTERS
5911 /* If possible, send signals to the entire pgrp
5912 by sending an input character to it. */
5913
5914 struct termios t;
5915 cc_t *sig_char = NULL;
5916
5917 tcgetattr (p->infd, &t);
5918
5919 switch (signo)
5920 {
5921 case SIGINT:
5922 sig_char = &t.c_cc[VINTR];
5923 break;
5924
5925 case SIGQUIT:
5926 sig_char = &t.c_cc[VQUIT];
5927 break;
5928
5929 case SIGTSTP:
5930 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5931 sig_char = &t.c_cc[VSWTCH];
5932 #else
5933 sig_char = &t.c_cc[VSUSP];
5934 #endif
5935 break;
5936 }
5937
5938 if (sig_char && *sig_char != CDISABLE)
5939 {
5940 send_process (proc, sig_char, 1, Qnil);
5941 return;
5942 }
5943 /* If we can't send the signal with a character,
5944 fall through and send it another way. */
5945
5946 /* The code above may fall through if it can't
5947 handle the signal. */
5948 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
5949
5950 #ifdef TIOCGPGRP
5951 /* Get the current pgrp using the tty itself, if we have that.
5952 Otherwise, use the pty to get the pgrp.
5953 On pfa systems, saka@pfu.fujitsu.co.JP writes:
5954 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5955 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
5956 His patch indicates that if TIOCGPGRP returns an error, then
5957 we should just assume that p->pid is also the process group id. */
5958
5959 gid = emacs_get_tty_pgrp (p);
5960
5961 if (gid == -1)
5962 /* If we can't get the information, assume
5963 the shell owns the tty. */
5964 gid = p->pid;
5965
5966 /* It is not clear whether anything really can set GID to -1.
5967 Perhaps on some system one of those ioctls can or could do so.
5968 Or perhaps this is vestigial. */
5969 if (gid == -1)
5970 no_pgrp = 1;
5971 #else /* ! defined (TIOCGPGRP ) */
5972 /* Can't select pgrps on this system, so we know that
5973 the child itself heads the pgrp. */
5974 gid = p->pid;
5975 #endif /* ! defined (TIOCGPGRP ) */
5976
5977 /* If current_group is lambda, and the shell owns the terminal,
5978 don't send any signal. */
5979 if (EQ (current_group, Qlambda) && gid == p->pid)
5980 return;
5981 }
5982
5983 switch (signo)
5984 {
5985 #ifdef SIGCONT
5986 case SIGCONT:
5987 p->raw_status_new = 0;
5988 p->status = Qrun;
5989 p->tick = ++process_tick;
5990 if (!nomsg)
5991 {
5992 status_notify (NULL);
5993 redisplay_preserve_echo_area (13);
5994 }
5995 break;
5996 #endif /* ! defined (SIGCONT) */
5997 case SIGINT:
5998 case SIGQUIT:
5999 case SIGKILL:
6000 flush_pending_output (p->infd);
6001 break;
6002 }
6003
6004 /* If we don't have process groups, send the signal to the immediate
6005 subprocess. That isn't really right, but it's better than any
6006 obvious alternative. */
6007 if (no_pgrp)
6008 {
6009 kill (p->pid, signo);
6010 return;
6011 }
6012
6013 /* gid may be a pid, or minus a pgrp's number */
6014 #ifdef TIOCSIGSEND
6015 if (!NILP (current_group))
6016 {
6017 if (ioctl (p->infd, TIOCSIGSEND, signo) == -1)
6018 EMACS_KILLPG (gid, signo);
6019 }
6020 else
6021 {
6022 gid = - p->pid;
6023 kill (gid, signo);
6024 }
6025 #else /* ! defined (TIOCSIGSEND) */
6026 EMACS_KILLPG (gid, signo);
6027 #endif /* ! defined (TIOCSIGSEND) */
6028 }
6029
6030 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
6031 doc: /* Interrupt process PROCESS.
6032 PROCESS may be a process, a buffer, or the name of a process or buffer.
6033 No arg or nil means current buffer's process.
6034 Second arg CURRENT-GROUP non-nil means send signal to
6035 the current process-group of the process's controlling terminal
6036 rather than to the process's own process group.
6037 If the process is a shell, this means interrupt current subjob
6038 rather than the shell.
6039
6040 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6041 don't send the signal. */)
6042 (Lisp_Object process, Lisp_Object current_group)
6043 {
6044 process_send_signal (process, SIGINT, current_group, 0);
6045 return process;
6046 }
6047
6048 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6049 doc: /* Kill process PROCESS. May be process or name of one.
6050 See function `interrupt-process' for more details on usage. */)
6051 (Lisp_Object process, Lisp_Object current_group)
6052 {
6053 process_send_signal (process, SIGKILL, current_group, 0);
6054 return process;
6055 }
6056
6057 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6058 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6059 See function `interrupt-process' for more details on usage. */)
6060 (Lisp_Object process, Lisp_Object current_group)
6061 {
6062 process_send_signal (process, SIGQUIT, current_group, 0);
6063 return process;
6064 }
6065
6066 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6067 doc: /* Stop process PROCESS. May be process or name of one.
6068 See function `interrupt-process' for more details on usage.
6069 If PROCESS is a network or serial process, inhibit handling of incoming
6070 traffic. */)
6071 (Lisp_Object process, Lisp_Object current_group)
6072 {
6073 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
6074 {
6075 struct Lisp_Process *p;
6076
6077 p = XPROCESS (process);
6078 if (NILP (p->command)
6079 && p->infd >= 0)
6080 {
6081 FD_CLR (p->infd, &input_wait_mask);
6082 FD_CLR (p->infd, &non_keyboard_wait_mask);
6083 }
6084 p->command = Qt;
6085 return process;
6086 }
6087 #ifndef SIGTSTP
6088 error ("No SIGTSTP support");
6089 #else
6090 process_send_signal (process, SIGTSTP, current_group, 0);
6091 #endif
6092 return process;
6093 }
6094
6095 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6096 doc: /* Continue process PROCESS. May be process or name of one.
6097 See function `interrupt-process' for more details on usage.
6098 If PROCESS is a network or serial process, resume handling of incoming
6099 traffic. */)
6100 (Lisp_Object process, Lisp_Object current_group)
6101 {
6102 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
6103 {
6104 struct Lisp_Process *p;
6105
6106 p = XPROCESS (process);
6107 if (EQ (p->command, Qt)
6108 && p->infd >= 0
6109 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6110 {
6111 FD_SET (p->infd, &input_wait_mask);
6112 FD_SET (p->infd, &non_keyboard_wait_mask);
6113 #ifdef WINDOWSNT
6114 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6115 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6116 #else /* not WINDOWSNT */
6117 tcflush (p->infd, TCIFLUSH);
6118 #endif /* not WINDOWSNT */
6119 }
6120 p->command = Qnil;
6121 return process;
6122 }
6123 #ifdef SIGCONT
6124 process_send_signal (process, SIGCONT, current_group, 0);
6125 #else
6126 error ("No SIGCONT support");
6127 #endif
6128 return process;
6129 }
6130
6131 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6132 2, 2, "sProcess (name or number): \nnSignal code: ",
6133 doc: /* Send PROCESS the signal with code SIGCODE.
6134 PROCESS may also be a number specifying the process id of the
6135 process to signal; in this case, the process need not be a child of
6136 this Emacs.
6137 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6138 (Lisp_Object process, Lisp_Object sigcode)
6139 {
6140 pid_t pid;
6141
6142 if (INTEGERP (process))
6143 {
6144 pid = XINT (process);
6145 goto got_it;
6146 }
6147
6148 if (FLOATP (process))
6149 {
6150 pid = (pid_t) XFLOAT_DATA (process);
6151 goto got_it;
6152 }
6153
6154 if (STRINGP (process))
6155 {
6156 Lisp_Object tem;
6157 if (tem = Fget_process (process), NILP (tem))
6158 {
6159 pid = XINT (Fstring_to_number (process, make_number (10)));
6160 if (pid > 0)
6161 goto got_it;
6162 }
6163 process = tem;
6164 }
6165 else
6166 process = get_process (process);
6167
6168 if (NILP (process))
6169 return process;
6170
6171 CHECK_PROCESS (process);
6172 pid = XPROCESS (process)->pid;
6173 if (pid <= 0)
6174 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6175
6176 got_it:
6177
6178 #define parse_signal(NAME, VALUE) \
6179 else if (!xstrcasecmp (name, NAME)) \
6180 XSETINT (sigcode, VALUE)
6181
6182 if (INTEGERP (sigcode))
6183 ;
6184 else
6185 {
6186 unsigned char *name;
6187
6188 CHECK_SYMBOL (sigcode);
6189 name = SDATA (SYMBOL_NAME (sigcode));
6190
6191 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
6192 name += 3;
6193
6194 if (0)
6195 ;
6196 #ifdef SIGUSR1
6197 parse_signal ("usr1", SIGUSR1);
6198 #endif
6199 #ifdef SIGUSR2
6200 parse_signal ("usr2", SIGUSR2);
6201 #endif
6202 #ifdef SIGTERM
6203 parse_signal ("term", SIGTERM);
6204 #endif
6205 #ifdef SIGHUP
6206 parse_signal ("hup", SIGHUP);
6207 #endif
6208 #ifdef SIGINT
6209 parse_signal ("int", SIGINT);
6210 #endif
6211 #ifdef SIGQUIT
6212 parse_signal ("quit", SIGQUIT);
6213 #endif
6214 #ifdef SIGILL
6215 parse_signal ("ill", SIGILL);
6216 #endif
6217 #ifdef SIGABRT
6218 parse_signal ("abrt", SIGABRT);
6219 #endif
6220 #ifdef SIGEMT
6221 parse_signal ("emt", SIGEMT);
6222 #endif
6223 #ifdef SIGKILL
6224 parse_signal ("kill", SIGKILL);
6225 #endif
6226 #ifdef SIGFPE
6227 parse_signal ("fpe", SIGFPE);
6228 #endif
6229 #ifdef SIGBUS
6230 parse_signal ("bus", SIGBUS);
6231 #endif
6232 #ifdef SIGSEGV
6233 parse_signal ("segv", SIGSEGV);
6234 #endif
6235 #ifdef SIGSYS
6236 parse_signal ("sys", SIGSYS);
6237 #endif
6238 #ifdef SIGPIPE
6239 parse_signal ("pipe", SIGPIPE);
6240 #endif
6241 #ifdef SIGALRM
6242 parse_signal ("alrm", SIGALRM);
6243 #endif
6244 #ifdef SIGURG
6245 parse_signal ("urg", SIGURG);
6246 #endif
6247 #ifdef SIGSTOP
6248 parse_signal ("stop", SIGSTOP);
6249 #endif
6250 #ifdef SIGTSTP
6251 parse_signal ("tstp", SIGTSTP);
6252 #endif
6253 #ifdef SIGCONT
6254 parse_signal ("cont", SIGCONT);
6255 #endif
6256 #ifdef SIGCHLD
6257 parse_signal ("chld", SIGCHLD);
6258 #endif
6259 #ifdef SIGTTIN
6260 parse_signal ("ttin", SIGTTIN);
6261 #endif
6262 #ifdef SIGTTOU
6263 parse_signal ("ttou", SIGTTOU);
6264 #endif
6265 #ifdef SIGIO
6266 parse_signal ("io", SIGIO);
6267 #endif
6268 #ifdef SIGXCPU
6269 parse_signal ("xcpu", SIGXCPU);
6270 #endif
6271 #ifdef SIGXFSZ
6272 parse_signal ("xfsz", SIGXFSZ);
6273 #endif
6274 #ifdef SIGVTALRM
6275 parse_signal ("vtalrm", SIGVTALRM);
6276 #endif
6277 #ifdef SIGPROF
6278 parse_signal ("prof", SIGPROF);
6279 #endif
6280 #ifdef SIGWINCH
6281 parse_signal ("winch", SIGWINCH);
6282 #endif
6283 #ifdef SIGINFO
6284 parse_signal ("info", SIGINFO);
6285 #endif
6286 else
6287 error ("Undefined signal name %s", name);
6288 }
6289
6290 #undef parse_signal
6291
6292 return make_number (kill (pid, XINT (sigcode)));
6293 }
6294
6295 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6296 doc: /* Make PROCESS see end-of-file in its input.
6297 EOF comes after any text already sent to it.
6298 PROCESS may be a process, a buffer, the name of a process or buffer, or
6299 nil, indicating the current buffer's process.
6300 If PROCESS is a network connection, or is a process communicating
6301 through a pipe (as opposed to a pty), then you cannot send any more
6302 text to PROCESS after you call this function.
6303 If PROCESS is a serial process, wait until all output written to the
6304 process has been transmitted to the serial port. */)
6305 (Lisp_Object process)
6306 {
6307 Lisp_Object proc;
6308 struct coding_system *coding;
6309
6310 if (DATAGRAM_CONN_P (process))
6311 return process;
6312
6313 proc = get_process (process);
6314 coding = proc_encode_coding_system[XPROCESS (proc)->outfd];
6315
6316 /* Make sure the process is really alive. */
6317 if (XPROCESS (proc)->raw_status_new)
6318 update_status (XPROCESS (proc));
6319 if (! EQ (XPROCESS (proc)->status, Qrun))
6320 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6321
6322 if (CODING_REQUIRE_FLUSHING (coding))
6323 {
6324 coding->mode |= CODING_MODE_LAST_BLOCK;
6325 send_process (proc, "", 0, Qnil);
6326 }
6327
6328 if (XPROCESS (proc)->pty_flag)
6329 send_process (proc, "\004", 1, Qnil);
6330 else if (EQ (XPROCESS (proc)->type, Qserial))
6331 {
6332 #ifndef WINDOWSNT
6333 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6334 error ("tcdrain() failed: %s", emacs_strerror (errno));
6335 #endif /* not WINDOWSNT */
6336 /* Do nothing on Windows because writes are blocking. */
6337 }
6338 else
6339 {
6340 int old_outfd, new_outfd;
6341
6342 #ifdef HAVE_SHUTDOWN
6343 /* If this is a network connection, or socketpair is used
6344 for communication with the subprocess, call shutdown to cause EOF.
6345 (In some old system, shutdown to socketpair doesn't work.
6346 Then we just can't win.) */
6347 if (EQ (XPROCESS (proc)->type, Qnetwork)
6348 || XPROCESS (proc)->outfd == XPROCESS (proc)->infd)
6349 shutdown (XPROCESS (proc)->outfd, 1);
6350 /* In case of socketpair, outfd == infd, so don't close it. */
6351 if (XPROCESS (proc)->outfd != XPROCESS (proc)->infd)
6352 emacs_close (XPROCESS (proc)->outfd);
6353 #else /* not HAVE_SHUTDOWN */
6354 emacs_close (XPROCESS (proc)->outfd);
6355 #endif /* not HAVE_SHUTDOWN */
6356 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6357 if (new_outfd < 0)
6358 abort ();
6359 old_outfd = XPROCESS (proc)->outfd;
6360
6361 if (!proc_encode_coding_system[new_outfd])
6362 proc_encode_coding_system[new_outfd]
6363 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
6364 memcpy (proc_encode_coding_system[new_outfd],
6365 proc_encode_coding_system[old_outfd],
6366 sizeof (struct coding_system));
6367 memset (proc_encode_coding_system[old_outfd], 0,
6368 sizeof (struct coding_system));
6369
6370 XPROCESS (proc)->outfd = new_outfd;
6371 }
6372 return process;
6373 }
6374 \f
6375 /* On receipt of a signal that a child status has changed, loop asking
6376 about children with changed statuses until the system says there
6377 are no more.
6378
6379 All we do is change the status; we do not run sentinels or print
6380 notifications. That is saved for the next time keyboard input is
6381 done, in order to avoid timing errors.
6382
6383 ** WARNING: this can be called during garbage collection.
6384 Therefore, it must not be fooled by the presence of mark bits in
6385 Lisp objects.
6386
6387 ** USG WARNING: Although it is not obvious from the documentation
6388 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6389 signal() before executing at least one wait(), otherwise the
6390 handler will be called again, resulting in an infinite loop. The
6391 relevant portion of the documentation reads "SIGCLD signals will be
6392 queued and the signal-catching function will be continually
6393 reentered until the queue is empty". Invoking signal() causes the
6394 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6395 Inc.
6396
6397 ** Malloc WARNING: This should never call malloc either directly or
6398 indirectly; if it does, that is a bug */
6399
6400 #ifdef SIGCHLD
6401 SIGTYPE
6402 sigchld_handler (int signo)
6403 {
6404 int old_errno = errno;
6405 Lisp_Object proc;
6406 struct Lisp_Process *p;
6407
6408 SIGNAL_THREAD_CHECK (signo);
6409
6410 while (1)
6411 {
6412 pid_t pid;
6413 int w;
6414 Lisp_Object tail;
6415
6416 #ifdef WNOHANG
6417 #ifndef WUNTRACED
6418 #define WUNTRACED 0
6419 #endif /* no WUNTRACED */
6420 /* Keep trying to get a status until we get a definitive result. */
6421 do
6422 {
6423 errno = 0;
6424 pid = wait3 (&w, WNOHANG | WUNTRACED, 0);
6425 }
6426 while (pid < 0 && errno == EINTR);
6427
6428 if (pid <= 0)
6429 {
6430 /* PID == 0 means no processes found, PID == -1 means a real
6431 failure. We have done all our job, so return. */
6432
6433 errno = old_errno;
6434 return;
6435 }
6436 #else
6437 pid = wait (&w);
6438 #endif /* no WNOHANG */
6439
6440 /* Find the process that signaled us, and record its status. */
6441
6442 /* The process can have been deleted by Fdelete_process. */
6443 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6444 {
6445 Lisp_Object xpid = XCAR (tail);
6446 if ((INTEGERP (xpid) && pid == (pid_t) XINT (xpid))
6447 || (FLOATP (xpid) && pid == (pid_t) XFLOAT_DATA (xpid)))
6448 {
6449 XSETCAR (tail, Qnil);
6450 goto sigchld_end_of_loop;
6451 }
6452 }
6453
6454 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6455 p = 0;
6456 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6457 {
6458 proc = XCDR (XCAR (tail));
6459 p = XPROCESS (proc);
6460 if (EQ (p->type, Qreal) && p->pid == pid)
6461 break;
6462 p = 0;
6463 }
6464
6465 /* Look for an asynchronous process whose pid hasn't been filled
6466 in yet. */
6467 if (p == 0)
6468 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6469 {
6470 proc = XCDR (XCAR (tail));
6471 p = XPROCESS (proc);
6472 if (p->pid == -1)
6473 break;
6474 p = 0;
6475 }
6476
6477 /* Change the status of the process that was found. */
6478 if (p != 0)
6479 {
6480 int clear_desc_flag = 0;
6481
6482 p->tick = ++process_tick;
6483 p->raw_status = w;
6484 p->raw_status_new = 1;
6485
6486 /* If process has terminated, stop waiting for its output. */
6487 if ((WIFSIGNALED (w) || WIFEXITED (w))
6488 && p->infd >= 0)
6489 clear_desc_flag = 1;
6490
6491 /* We use clear_desc_flag to avoid a compiler bug in Microsoft C. */
6492 if (clear_desc_flag)
6493 {
6494 FD_CLR (p->infd, &input_wait_mask);
6495 FD_CLR (p->infd, &non_keyboard_wait_mask);
6496 }
6497
6498 /* Tell wait_reading_process_output that it needs to wake up and
6499 look around. */
6500 if (input_available_clear_time)
6501 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6502 }
6503
6504 /* There was no asynchronous process found for that pid: we have
6505 a synchronous process. */
6506 else
6507 {
6508 synch_process_alive = 0;
6509
6510 /* Report the status of the synchronous process. */
6511 if (WIFEXITED (w))
6512 synch_process_retcode = WRETCODE (w);
6513 else if (WIFSIGNALED (w))
6514 synch_process_termsig = WTERMSIG (w);
6515
6516 /* Tell wait_reading_process_output that it needs to wake up and
6517 look around. */
6518 if (input_available_clear_time)
6519 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6520 }
6521
6522 sigchld_end_of_loop:
6523 ;
6524
6525 /* On some systems, we must return right away.
6526 If any more processes want to signal us, we will
6527 get another signal.
6528 Otherwise (on systems that have WNOHANG), loop around
6529 to use up all the processes that have something to tell us. */
6530 #if (defined WINDOWSNT \
6531 || (defined USG && !defined GNU_LINUX \
6532 && !(defined HPUX && defined WNOHANG)))
6533 errno = old_errno;
6534 return;
6535 #endif /* USG, but not HPUX with WNOHANG */
6536 }
6537 }
6538 #endif /* SIGCHLD */
6539 \f
6540
6541 static Lisp_Object
6542 exec_sentinel_unwind (Lisp_Object data)
6543 {
6544 XPROCESS (XCAR (data))->sentinel = XCDR (data);
6545 return Qnil;
6546 }
6547
6548 static Lisp_Object
6549 exec_sentinel_error_handler (Lisp_Object error)
6550 {
6551 cmd_error_internal (error, "error in process sentinel: ");
6552 Vinhibit_quit = Qt;
6553 update_echo_area ();
6554 Fsleep_for (make_number (2), Qnil);
6555 return Qt;
6556 }
6557
6558 static void
6559 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6560 {
6561 Lisp_Object sentinel, obuffer, odeactivate, okeymap;
6562 register struct Lisp_Process *p = XPROCESS (proc);
6563 int count = SPECPDL_INDEX ();
6564 int outer_running_asynch_code = running_asynch_code;
6565 int waiting = waiting_for_user_input_p;
6566
6567 if (inhibit_sentinels)
6568 return;
6569
6570 /* No need to gcpro these, because all we do with them later
6571 is test them for EQness, and none of them should be a string. */
6572 odeactivate = Vdeactivate_mark;
6573 XSETBUFFER (obuffer, current_buffer);
6574 okeymap = current_buffer->keymap;
6575
6576 /* There's no good reason to let sentinels change the current
6577 buffer, and many callers of accept-process-output, sit-for, and
6578 friends don't expect current-buffer to be changed from under them. */
6579 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
6580
6581 sentinel = p->sentinel;
6582 if (NILP (sentinel))
6583 return;
6584
6585 /* Zilch the sentinel while it's running, to avoid recursive invocations;
6586 assure that it gets restored no matter how the sentinel exits. */
6587 p->sentinel = Qnil;
6588 record_unwind_protect (exec_sentinel_unwind, Fcons (proc, sentinel));
6589 /* Inhibit quit so that random quits don't screw up a running filter. */
6590 specbind (Qinhibit_quit, Qt);
6591 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6592
6593 /* In case we get recursively called,
6594 and we already saved the match data nonrecursively,
6595 save the same match data in safely recursive fashion. */
6596 if (outer_running_asynch_code)
6597 {
6598 Lisp_Object tem;
6599 tem = Fmatch_data (Qnil, Qnil, Qnil);
6600 restore_search_regs ();
6601 record_unwind_save_match_data ();
6602 Fset_match_data (tem, Qt);
6603 }
6604
6605 /* For speed, if a search happens within this code,
6606 save the match data in a special nonrecursive fashion. */
6607 running_asynch_code = 1;
6608
6609 internal_condition_case_1 (read_process_output_call,
6610 Fcons (sentinel,
6611 Fcons (proc, Fcons (reason, Qnil))),
6612 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6613 exec_sentinel_error_handler);
6614
6615 /* If we saved the match data nonrecursively, restore it now. */
6616 restore_search_regs ();
6617 running_asynch_code = outer_running_asynch_code;
6618
6619 Vdeactivate_mark = odeactivate;
6620
6621 /* Restore waiting_for_user_input_p as it was
6622 when we were called, in case the filter clobbered it. */
6623 waiting_for_user_input_p = waiting;
6624
6625 #if 0
6626 if (! EQ (Fcurrent_buffer (), obuffer)
6627 || ! EQ (current_buffer->keymap, okeymap))
6628 #endif
6629 /* But do it only if the caller is actually going to read events.
6630 Otherwise there's no need to make him wake up, and it could
6631 cause trouble (for example it would make sit_for return). */
6632 if (waiting_for_user_input_p == -1)
6633 record_asynch_buffer_change ();
6634
6635 unbind_to (count, Qnil);
6636 }
6637
6638 /* Report all recent events of a change in process status
6639 (either run the sentinel or output a message).
6640 This is usually done while Emacs is waiting for keyboard input
6641 but can be done at other times. */
6642
6643 static void
6644 status_notify (struct Lisp_Process *deleting_process)
6645 {
6646 register Lisp_Object proc, buffer;
6647 Lisp_Object tail, msg;
6648 struct gcpro gcpro1, gcpro2;
6649
6650 tail = Qnil;
6651 msg = Qnil;
6652 /* We need to gcpro tail; if read_process_output calls a filter
6653 which deletes a process and removes the cons to which tail points
6654 from Vprocess_alist, and then causes a GC, tail is an unprotected
6655 reference. */
6656 GCPRO2 (tail, msg);
6657
6658 /* Set this now, so that if new processes are created by sentinels
6659 that we run, we get called again to handle their status changes. */
6660 update_tick = process_tick;
6661
6662 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6663 {
6664 Lisp_Object symbol;
6665 register struct Lisp_Process *p;
6666
6667 proc = Fcdr (XCAR (tail));
6668 p = XPROCESS (proc);
6669
6670 if (p->tick != p->update_tick)
6671 {
6672 p->update_tick = p->tick;
6673
6674 /* If process is still active, read any output that remains. */
6675 while (! EQ (p->filter, Qt)
6676 && ! EQ (p->status, Qconnect)
6677 && ! EQ (p->status, Qlisten)
6678 /* Network or serial process not stopped: */
6679 && ! EQ (p->command, Qt)
6680 && p->infd >= 0
6681 && p != deleting_process
6682 && read_process_output (proc, p->infd) > 0);
6683
6684 buffer = p->buffer;
6685
6686 /* Get the text to use for the message. */
6687 if (p->raw_status_new)
6688 update_status (p);
6689 msg = status_message (p);
6690
6691 /* If process is terminated, deactivate it or delete it. */
6692 symbol = p->status;
6693 if (CONSP (p->status))
6694 symbol = XCAR (p->status);
6695
6696 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6697 || EQ (symbol, Qclosed))
6698 {
6699 if (delete_exited_processes)
6700 remove_process (proc);
6701 else
6702 deactivate_process (proc);
6703 }
6704
6705 /* The actions above may have further incremented p->tick.
6706 So set p->update_tick again
6707 so that an error in the sentinel will not cause
6708 this code to be run again. */
6709 p->update_tick = p->tick;
6710 /* Now output the message suitably. */
6711 if (!NILP (p->sentinel))
6712 exec_sentinel (proc, msg);
6713 /* Don't bother with a message in the buffer
6714 when a process becomes runnable. */
6715 else if (!EQ (symbol, Qrun) && !NILP (buffer))
6716 {
6717 Lisp_Object tem;
6718 struct buffer *old = current_buffer;
6719 EMACS_INT opoint, opoint_byte;
6720 EMACS_INT before, before_byte;
6721
6722 /* Avoid error if buffer is deleted
6723 (probably that's why the process is dead, too) */
6724 if (NILP (XBUFFER (buffer)->name))
6725 continue;
6726 Fset_buffer (buffer);
6727
6728 opoint = PT;
6729 opoint_byte = PT_BYTE;
6730 /* Insert new output into buffer
6731 at the current end-of-output marker,
6732 thus preserving logical ordering of input and output. */
6733 if (XMARKER (p->mark)->buffer)
6734 Fgoto_char (p->mark);
6735 else
6736 SET_PT_BOTH (ZV, ZV_BYTE);
6737
6738 before = PT;
6739 before_byte = PT_BYTE;
6740
6741 tem = current_buffer->read_only;
6742 current_buffer->read_only = Qnil;
6743 insert_string ("\nProcess ");
6744 Finsert (1, &p->name);
6745 insert_string (" ");
6746 Finsert (1, &msg);
6747 current_buffer->read_only = tem;
6748 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6749
6750 if (opoint >= before)
6751 SET_PT_BOTH (opoint + (PT - before),
6752 opoint_byte + (PT_BYTE - before_byte));
6753 else
6754 SET_PT_BOTH (opoint, opoint_byte);
6755
6756 set_buffer_internal (old);
6757 }
6758 }
6759 } /* end for */
6760
6761 update_mode_lines++; /* in case buffers use %s in mode-line-format */
6762 UNGCPRO;
6763 }
6764
6765 \f
6766 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6767 Sset_process_coding_system, 1, 3, 0,
6768 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6769 DECODING will be used to decode subprocess output and ENCODING to
6770 encode subprocess input. */)
6771 (register Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
6772 {
6773 register struct Lisp_Process *p;
6774
6775 CHECK_PROCESS (process);
6776 p = XPROCESS (process);
6777 if (p->infd < 0)
6778 error ("Input file descriptor of %s closed", SDATA (p->name));
6779 if (p->outfd < 0)
6780 error ("Output file descriptor of %s closed", SDATA (p->name));
6781 Fcheck_coding_system (decoding);
6782 Fcheck_coding_system (encoding);
6783 encoding = coding_inherit_eol_type (encoding, Qnil);
6784 p->decode_coding_system = decoding;
6785 p->encode_coding_system = encoding;
6786 setup_process_coding_systems (process);
6787
6788 return Qnil;
6789 }
6790
6791 DEFUN ("process-coding-system",
6792 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6793 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6794 (register Lisp_Object process)
6795 {
6796 CHECK_PROCESS (process);
6797 return Fcons (XPROCESS (process)->decode_coding_system,
6798 XPROCESS (process)->encode_coding_system);
6799 }
6800
6801 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6802 Sset_process_filter_multibyte, 2, 2, 0,
6803 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6804 If FLAG is non-nil, the filter is given multibyte strings.
6805 If FLAG is nil, the filter is given unibyte strings. In this case,
6806 all character code conversion except for end-of-line conversion is
6807 suppressed. */)
6808 (Lisp_Object process, Lisp_Object flag)
6809 {
6810 register struct Lisp_Process *p;
6811
6812 CHECK_PROCESS (process);
6813 p = XPROCESS (process);
6814 if (NILP (flag))
6815 p->decode_coding_system = raw_text_coding_system (p->decode_coding_system);
6816 setup_process_coding_systems (process);
6817
6818 return Qnil;
6819 }
6820
6821 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6822 Sprocess_filter_multibyte_p, 1, 1, 0,
6823 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6824 (Lisp_Object process)
6825 {
6826 register struct Lisp_Process *p;
6827 struct coding_system *coding;
6828
6829 CHECK_PROCESS (process);
6830 p = XPROCESS (process);
6831 coding = proc_decode_coding_system[p->infd];
6832 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6833 }
6834
6835
6836 \f
6837
6838 void
6839 add_gpm_wait_descriptor (int desc)
6840 {
6841 add_keyboard_wait_descriptor (desc);
6842 }
6843
6844 void
6845 delete_gpm_wait_descriptor (int desc)
6846 {
6847 delete_keyboard_wait_descriptor (desc);
6848 }
6849
6850 /* Return nonzero if *MASK has a bit set
6851 that corresponds to one of the keyboard input descriptors. */
6852
6853 static int
6854 keyboard_bit_set (fd_set *mask)
6855 {
6856 int fd;
6857
6858 for (fd = 0; fd <= max_input_desc; fd++)
6859 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6860 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6861 return 1;
6862
6863 return 0;
6864 }
6865
6866 #else /* not subprocesses */
6867
6868 /* Defined on msdos.c. */
6869 extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
6870 EMACS_TIME *);
6871
6872 /* Implementation of wait_reading_process_output, assuming that there
6873 are no subprocesses. Used only by the MS-DOS build.
6874
6875 Wait for timeout to elapse and/or keyboard input to be available.
6876
6877 time_limit is:
6878 timeout in seconds, or
6879 zero for no limit, or
6880 -1 means gobble data immediately available but don't wait for any.
6881
6882 read_kbd is a Lisp_Object:
6883 0 to ignore keyboard input, or
6884 1 to return when input is available, or
6885 -1 means caller will actually read the input, so don't throw to
6886 the quit handler.
6887
6888 see full version for other parameters. We know that wait_proc will
6889 always be NULL, since `subprocesses' isn't defined.
6890
6891 do_display != 0 means redisplay should be done to show subprocess
6892 output that arrives.
6893
6894 Return true if we received input from any process. */
6895
6896 int
6897 wait_reading_process_output (int time_limit, int microsecs, int read_kbd,
6898 int do_display,
6899 Lisp_Object wait_for_cell,
6900 struct Lisp_Process *wait_proc, int just_wait_proc)
6901 {
6902 register int nfds;
6903 EMACS_TIME end_time, timeout;
6904 SELECT_TYPE waitchannels;
6905 int xerrno;
6906
6907 /* What does time_limit really mean? */
6908 if (time_limit || microsecs)
6909 {
6910 EMACS_GET_TIME (end_time);
6911 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
6912 EMACS_ADD_TIME (end_time, end_time, timeout);
6913 }
6914
6915 /* Turn off periodic alarms (in case they are in use)
6916 and then turn off any other atimers,
6917 because the select emulator uses alarms. */
6918 stop_polling ();
6919 turn_on_atimers (0);
6920
6921 while (1)
6922 {
6923 int timeout_reduced_for_timers = 0;
6924
6925 /* If calling from keyboard input, do not quit
6926 since we want to return C-g as an input character.
6927 Otherwise, do pending quit if requested. */
6928 if (read_kbd >= 0)
6929 QUIT;
6930
6931 /* Exit now if the cell we're waiting for became non-nil. */
6932 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6933 break;
6934
6935 /* Compute time from now till when time limit is up */
6936 /* Exit if already run out */
6937 if (time_limit == -1)
6938 {
6939 /* -1 specified for timeout means
6940 gobble output available now
6941 but don't wait at all. */
6942
6943 EMACS_SET_SECS_USECS (timeout, 0, 0);
6944 }
6945 else if (time_limit || microsecs)
6946 {
6947 EMACS_GET_TIME (timeout);
6948 EMACS_SUB_TIME (timeout, end_time, timeout);
6949 if (EMACS_TIME_NEG_P (timeout))
6950 break;
6951 }
6952 else
6953 {
6954 EMACS_SET_SECS_USECS (timeout, 100000, 0);
6955 }
6956
6957 /* If our caller will not immediately handle keyboard events,
6958 run timer events directly.
6959 (Callers that will immediately read keyboard events
6960 call timer_delay on their own.) */
6961 if (NILP (wait_for_cell))
6962 {
6963 EMACS_TIME timer_delay;
6964
6965 do
6966 {
6967 int old_timers_run = timers_run;
6968 timer_delay = timer_check (1);
6969 if (timers_run != old_timers_run && do_display)
6970 /* We must retry, since a timer may have requeued itself
6971 and that could alter the time delay. */
6972 redisplay_preserve_echo_area (14);
6973 else
6974 break;
6975 }
6976 while (!detect_input_pending ());
6977
6978 /* If there is unread keyboard input, also return. */
6979 if (read_kbd != 0
6980 && requeued_events_pending_p ())
6981 break;
6982
6983 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
6984 {
6985 EMACS_TIME difference;
6986 EMACS_SUB_TIME (difference, timer_delay, timeout);
6987 if (EMACS_TIME_NEG_P (difference))
6988 {
6989 timeout = timer_delay;
6990 timeout_reduced_for_timers = 1;
6991 }
6992 }
6993 }
6994
6995 /* Cause C-g and alarm signals to take immediate action,
6996 and cause input available signals to zero out timeout. */
6997 if (read_kbd < 0)
6998 set_waiting_for_input (&timeout);
6999
7000 /* Wait till there is something to do. */
7001
7002 if (! read_kbd && NILP (wait_for_cell))
7003 FD_ZERO (&waitchannels);
7004 else
7005 FD_SET (0, &waitchannels);
7006
7007 /* If a frame has been newly mapped and needs updating,
7008 reprocess its display stuff. */
7009 if (frame_garbaged && do_display)
7010 {
7011 clear_waiting_for_input ();
7012 redisplay_preserve_echo_area (15);
7013 if (read_kbd < 0)
7014 set_waiting_for_input (&timeout);
7015 }
7016
7017 if (read_kbd && detect_input_pending ())
7018 {
7019 nfds = 0;
7020 FD_ZERO (&waitchannels);
7021 }
7022 else
7023 nfds = select (1, &waitchannels, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
7024 &timeout);
7025
7026 xerrno = errno;
7027
7028 /* Make C-g and alarm signals set flags again */
7029 clear_waiting_for_input ();
7030
7031 /* If we woke up due to SIGWINCH, actually change size now. */
7032 do_pending_window_change (0);
7033
7034 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
7035 /* We waited the full specified time, so return now. */
7036 break;
7037
7038 if (nfds == -1)
7039 {
7040 /* If the system call was interrupted, then go around the
7041 loop again. */
7042 if (xerrno == EINTR)
7043 FD_ZERO (&waitchannels);
7044 else
7045 error ("select error: %s", emacs_strerror (xerrno));
7046 }
7047
7048 /* Check for keyboard input */
7049
7050 if (read_kbd
7051 && detect_input_pending_run_timers (do_display))
7052 {
7053 swallow_events (do_display);
7054 if (detect_input_pending_run_timers (do_display))
7055 break;
7056 }
7057
7058 /* If there is unread keyboard input, also return. */
7059 if (read_kbd
7060 && requeued_events_pending_p ())
7061 break;
7062
7063 /* If wait_for_cell. check for keyboard input
7064 but don't run any timers.
7065 ??? (It seems wrong to me to check for keyboard
7066 input at all when wait_for_cell, but the code
7067 has been this way since July 1994.
7068 Try changing this after version 19.31.) */
7069 if (! NILP (wait_for_cell)
7070 && detect_input_pending ())
7071 {
7072 swallow_events (do_display);
7073 if (detect_input_pending ())
7074 break;
7075 }
7076
7077 /* Exit now if the cell we're waiting for became non-nil. */
7078 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7079 break;
7080 }
7081
7082 start_polling ();
7083
7084 return 0;
7085 }
7086
7087 #endif /* not subprocesses */
7088
7089 /* The following functions are needed even if async subprocesses are
7090 not supported. Some of them are no-op stubs in that case. */
7091
7092 /* Add DESC to the set of keyboard input descriptors. */
7093
7094 void
7095 add_keyboard_wait_descriptor (int desc)
7096 {
7097 #ifdef subprocesses /* actually means "not MSDOS" */
7098 FD_SET (desc, &input_wait_mask);
7099 FD_SET (desc, &non_process_wait_mask);
7100 if (desc > max_input_desc)
7101 max_input_desc = desc;
7102 #endif
7103 }
7104
7105 /* From now on, do not expect DESC to give keyboard input. */
7106
7107 void
7108 delete_keyboard_wait_descriptor (int desc)
7109 {
7110 #ifdef subprocesses
7111 int fd;
7112 int lim = max_input_desc;
7113
7114 FD_CLR (desc, &input_wait_mask);
7115 FD_CLR (desc, &non_process_wait_mask);
7116
7117 if (desc == max_input_desc)
7118 for (fd = 0; fd < lim; fd++)
7119 if (FD_ISSET (fd, &input_wait_mask) || FD_ISSET (fd, &write_mask))
7120 max_input_desc = fd;
7121 #endif
7122 }
7123
7124 /* Setup coding systems of PROCESS. */
7125
7126 void
7127 setup_process_coding_systems (Lisp_Object process)
7128 {
7129 #ifdef subprocesses
7130 struct Lisp_Process *p = XPROCESS (process);
7131 int inch = p->infd;
7132 int outch = p->outfd;
7133 Lisp_Object coding_system;
7134
7135 if (inch < 0 || outch < 0)
7136 return;
7137
7138 if (!proc_decode_coding_system[inch])
7139 proc_decode_coding_system[inch]
7140 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
7141 coding_system = p->decode_coding_system;
7142 if (! NILP (p->filter))
7143 ;
7144 else if (BUFFERP (p->buffer))
7145 {
7146 if (NILP (XBUFFER (p->buffer)->enable_multibyte_characters))
7147 coding_system = raw_text_coding_system (coding_system);
7148 }
7149 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
7150
7151 if (!proc_encode_coding_system[outch])
7152 proc_encode_coding_system[outch]
7153 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
7154 setup_coding_system (p->encode_coding_system,
7155 proc_encode_coding_system[outch]);
7156 #endif
7157 }
7158
7159 /* Close all descriptors currently in use for communication
7160 with subprocess. This is used in a newly-forked subprocess
7161 to get rid of irrelevant descriptors. */
7162
7163 void
7164 close_process_descs (void)
7165 {
7166 #ifndef DOS_NT
7167 int i;
7168 for (i = 0; i < MAXDESC; i++)
7169 {
7170 Lisp_Object process;
7171 process = chan_process[i];
7172 if (!NILP (process))
7173 {
7174 int in = XPROCESS (process)->infd;
7175 int out = XPROCESS (process)->outfd;
7176 if (in >= 0)
7177 emacs_close (in);
7178 if (out >= 0 && in != out)
7179 emacs_close (out);
7180 }
7181 }
7182 #endif
7183 }
7184
7185 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7186 doc: /* Return the (or a) process associated with BUFFER.
7187 BUFFER may be a buffer or the name of one. */)
7188 (register Lisp_Object buffer)
7189 {
7190 #ifdef subprocesses
7191 register Lisp_Object buf, tail, proc;
7192
7193 if (NILP (buffer)) return Qnil;
7194 buf = Fget_buffer (buffer);
7195 if (NILP (buf)) return Qnil;
7196
7197 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
7198 {
7199 proc = Fcdr (XCAR (tail));
7200 if (PROCESSP (proc) && EQ (XPROCESS (proc)->buffer, buf))
7201 return proc;
7202 }
7203 #endif /* subprocesses */
7204 return Qnil;
7205 }
7206
7207 DEFUN ("process-inherit-coding-system-flag",
7208 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7209 1, 1, 0,
7210 doc: /* Return the value of inherit-coding-system flag for PROCESS.
7211 If this flag is t, `buffer-file-coding-system' of the buffer
7212 associated with PROCESS will inherit the coding system used to decode
7213 the process output. */)
7214 (register Lisp_Object process)
7215 {
7216 #ifdef subprocesses
7217 CHECK_PROCESS (process);
7218 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
7219 #else
7220 /* Ignore the argument and return the value of
7221 inherit-process-coding-system. */
7222 return inherit_process_coding_system ? Qt : Qnil;
7223 #endif
7224 }
7225
7226 /* Kill all processes associated with `buffer'.
7227 If `buffer' is nil, kill all processes */
7228
7229 void
7230 kill_buffer_processes (Lisp_Object buffer)
7231 {
7232 #ifdef subprocesses
7233 Lisp_Object tail, proc;
7234
7235 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
7236 {
7237 proc = XCDR (XCAR (tail));
7238 if (PROCESSP (proc)
7239 && (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer)))
7240 {
7241 if (NETCONN_P (proc) || SERIALCONN_P (proc))
7242 Fdelete_process (proc);
7243 else if (XPROCESS (proc)->infd >= 0)
7244 process_send_signal (proc, SIGHUP, Qnil, 1);
7245 }
7246 }
7247 #else /* subprocesses */
7248 /* Since we have no subprocesses, this does nothing. */
7249 #endif /* subprocesses */
7250 }
7251
7252 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p, Swaiting_for_user_input_p,
7253 0, 0, 0,
7254 doc: /* Returns non-nil if Emacs is waiting for input from the user.
7255 This is intended for use by asynchronous process output filters and sentinels. */)
7256 (void)
7257 {
7258 #ifdef subprocesses
7259 return (waiting_for_user_input_p ? Qt : Qnil);
7260 #else
7261 return Qnil;
7262 #endif
7263 }
7264
7265 /* Stop reading input from keyboard sources. */
7266
7267 void
7268 hold_keyboard_input (void)
7269 {
7270 kbd_is_on_hold = 1;
7271 }
7272
7273 /* Resume reading input from keyboard sources. */
7274
7275 void
7276 unhold_keyboard_input (void)
7277 {
7278 kbd_is_on_hold = 0;
7279 }
7280
7281 /* Return non-zero if keyboard input is on hold, zero otherwise. */
7282
7283 int
7284 kbd_on_hold_p (void)
7285 {
7286 return kbd_is_on_hold;
7287 }
7288
7289 \f
7290 /* Enumeration of and access to system processes a-la ps(1). */
7291
7292 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7293 0, 0, 0,
7294 doc: /* Return a list of numerical process IDs of all running processes.
7295 If this functionality is unsupported, return nil.
7296
7297 See `process-attributes' for getting attributes of a process given its ID. */)
7298 (void)
7299 {
7300 return list_system_processes ();
7301 }
7302
7303 DEFUN ("process-attributes", Fprocess_attributes,
7304 Sprocess_attributes, 1, 1, 0,
7305 doc: /* Return attributes of the process given by its PID, a number.
7306
7307 Value is an alist where each element is a cons cell of the form
7308
7309 \(KEY . VALUE)
7310
7311 If this functionality is unsupported, the value is nil.
7312
7313 See `list-system-processes' for getting a list of all process IDs.
7314
7315 The KEYs of the attributes that this function may return are listed
7316 below, together with the type of the associated VALUE (in parentheses).
7317 Not all platforms support all of these attributes; unsupported
7318 attributes will not appear in the returned alist.
7319 Unless explicitly indicated otherwise, numbers can have either
7320 integer or floating point values.
7321
7322 euid -- Effective user User ID of the process (number)
7323 user -- User name corresponding to euid (string)
7324 egid -- Effective user Group ID of the process (number)
7325 group -- Group name corresponding to egid (string)
7326 comm -- Command name (executable name only) (string)
7327 state -- Process state code, such as "S", "R", or "T" (string)
7328 ppid -- Parent process ID (number)
7329 pgrp -- Process group ID (number)
7330 sess -- Session ID, i.e. process ID of session leader (number)
7331 ttname -- Controlling tty name (string)
7332 tpgid -- ID of foreground process group on the process's tty (number)
7333 minflt -- number of minor page faults (number)
7334 majflt -- number of major page faults (number)
7335 cminflt -- cumulative number of minor page faults (number)
7336 cmajflt -- cumulative number of major page faults (number)
7337 utime -- user time used by the process, in the (HIGH LOW USEC) format
7338 stime -- system time used by the process, in the (HIGH LOW USEC) format
7339 time -- sum of utime and stime, in the (HIGH LOW USEC) format
7340 cutime -- user time used by the process and its children, (HIGH LOW USEC)
7341 cstime -- system time used by the process and its children, (HIGH LOW USEC)
7342 ctime -- sum of cutime and cstime, in the (HIGH LOW USEC) format
7343 pri -- priority of the process (number)
7344 nice -- nice value of the process (number)
7345 thcount -- process thread count (number)
7346 start -- time the process started, in the (HIGH LOW USEC) format
7347 vsize -- virtual memory size of the process in KB's (number)
7348 rss -- resident set size of the process in KB's (number)
7349 etime -- elapsed time the process is running, in (HIGH LOW USEC) format
7350 pcpu -- percents of CPU time used by the process (floating-point number)
7351 pmem -- percents of total physical memory used by process's resident set
7352 (floating-point number)
7353 args -- command line which invoked the process (string). */)
7354 ( Lisp_Object pid)
7355 {
7356 return system_process_attributes (pid);
7357 }
7358
7359 \f
7360 void
7361 init_process (void)
7362 {
7363 #ifdef subprocesses
7364 register int i;
7365
7366 inhibit_sentinels = 0;
7367
7368 #ifdef SIGCHLD
7369 #ifndef CANNOT_DUMP
7370 if (! noninteractive || initialized)
7371 #endif
7372 signal (SIGCHLD, sigchld_handler);
7373 #endif
7374
7375 FD_ZERO (&input_wait_mask);
7376 FD_ZERO (&non_keyboard_wait_mask);
7377 FD_ZERO (&non_process_wait_mask);
7378 FD_ZERO (&write_mask);
7379 max_process_desc = 0;
7380 memset (fd_callback_info, 0, sizeof (fd_callback_info));
7381
7382 #ifdef NON_BLOCKING_CONNECT
7383 FD_ZERO (&connect_wait_mask);
7384 num_pending_connects = 0;
7385 #endif
7386
7387 #ifdef ADAPTIVE_READ_BUFFERING
7388 process_output_delay_count = 0;
7389 process_output_skip = 0;
7390 #endif
7391
7392 /* Don't do this, it caused infinite select loops. The display
7393 method should call add_keyboard_wait_descriptor on stdin if it
7394 needs that. */
7395 #if 0
7396 FD_SET (0, &input_wait_mask);
7397 #endif
7398
7399 Vprocess_alist = Qnil;
7400 #ifdef SIGCHLD
7401 deleted_pid_list = Qnil;
7402 #endif
7403 for (i = 0; i < MAXDESC; i++)
7404 {
7405 chan_process[i] = Qnil;
7406 proc_buffered_char[i] = -1;
7407 }
7408 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7409 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7410 #ifdef DATAGRAM_SOCKETS
7411 memset (datagram_address, 0, sizeof datagram_address);
7412 #endif
7413
7414 {
7415 Lisp_Object subfeatures = Qnil;
7416 const struct socket_options *sopt;
7417
7418 #define ADD_SUBFEATURE(key, val) \
7419 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7420
7421 #ifdef NON_BLOCKING_CONNECT
7422 ADD_SUBFEATURE (QCnowait, Qt);
7423 #endif
7424 #ifdef DATAGRAM_SOCKETS
7425 ADD_SUBFEATURE (QCtype, Qdatagram);
7426 #endif
7427 #ifdef HAVE_SEQPACKET
7428 ADD_SUBFEATURE (QCtype, Qseqpacket);
7429 #endif
7430 #ifdef HAVE_LOCAL_SOCKETS
7431 ADD_SUBFEATURE (QCfamily, Qlocal);
7432 #endif
7433 ADD_SUBFEATURE (QCfamily, Qipv4);
7434 #ifdef AF_INET6
7435 ADD_SUBFEATURE (QCfamily, Qipv6);
7436 #endif
7437 #ifdef HAVE_GETSOCKNAME
7438 ADD_SUBFEATURE (QCservice, Qt);
7439 #endif
7440 #if defined(O_NONBLOCK) || defined(O_NDELAY)
7441 ADD_SUBFEATURE (QCserver, Qt);
7442 #endif
7443
7444 for (sopt = socket_options; sopt->name; sopt++)
7445 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7446
7447 Fprovide (intern_c_string ("make-network-process"), subfeatures);
7448 }
7449
7450 #if defined (DARWIN_OS)
7451 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7452 processes. As such, we only change the default value. */
7453 if (initialized)
7454 {
7455 const char *release = get_operating_system_release ();
7456 if (!release || !release[0] || (release[0] < MIN_PTY_KERNEL_VERSION
7457 && release[1] == '.')) {
7458 Vprocess_connection_type = Qnil;
7459 }
7460 }
7461 #endif
7462 #endif /* subprocesses */
7463 kbd_is_on_hold = 0;
7464 }
7465
7466 void
7467 syms_of_process (void)
7468 {
7469 #ifdef subprocesses
7470
7471 Qprocessp = intern_c_string ("processp");
7472 staticpro (&Qprocessp);
7473 Qrun = intern_c_string ("run");
7474 staticpro (&Qrun);
7475 Qstop = intern_c_string ("stop");
7476 staticpro (&Qstop);
7477 Qsignal = intern_c_string ("signal");
7478 staticpro (&Qsignal);
7479
7480 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7481 here again.
7482
7483 Qexit = intern_c_string ("exit");
7484 staticpro (&Qexit); */
7485
7486 Qopen = intern_c_string ("open");
7487 staticpro (&Qopen);
7488 Qclosed = intern_c_string ("closed");
7489 staticpro (&Qclosed);
7490 Qconnect = intern_c_string ("connect");
7491 staticpro (&Qconnect);
7492 Qfailed = intern_c_string ("failed");
7493 staticpro (&Qfailed);
7494 Qlisten = intern_c_string ("listen");
7495 staticpro (&Qlisten);
7496 Qlocal = intern_c_string ("local");
7497 staticpro (&Qlocal);
7498 Qipv4 = intern_c_string ("ipv4");
7499 staticpro (&Qipv4);
7500 #ifdef AF_INET6
7501 Qipv6 = intern_c_string ("ipv6");
7502 staticpro (&Qipv6);
7503 #endif
7504 Qdatagram = intern_c_string ("datagram");
7505 staticpro (&Qdatagram);
7506 Qseqpacket = intern_c_string ("seqpacket");
7507 staticpro (&Qseqpacket);
7508
7509 QCport = intern_c_string (":port");
7510 staticpro (&QCport);
7511 QCspeed = intern_c_string (":speed");
7512 staticpro (&QCspeed);
7513 QCprocess = intern_c_string (":process");
7514 staticpro (&QCprocess);
7515
7516 QCbytesize = intern_c_string (":bytesize");
7517 staticpro (&QCbytesize);
7518 QCstopbits = intern_c_string (":stopbits");
7519 staticpro (&QCstopbits);
7520 QCparity = intern_c_string (":parity");
7521 staticpro (&QCparity);
7522 Qodd = intern_c_string ("odd");
7523 staticpro (&Qodd);
7524 Qeven = intern_c_string ("even");
7525 staticpro (&Qeven);
7526 QCflowcontrol = intern_c_string (":flowcontrol");
7527 staticpro (&QCflowcontrol);
7528 Qhw = intern_c_string ("hw");
7529 staticpro (&Qhw);
7530 Qsw = intern_c_string ("sw");
7531 staticpro (&Qsw);
7532 QCsummary = intern_c_string (":summary");
7533 staticpro (&QCsummary);
7534
7535 Qreal = intern_c_string ("real");
7536 staticpro (&Qreal);
7537 Qnetwork = intern_c_string ("network");
7538 staticpro (&Qnetwork);
7539 Qserial = intern_c_string ("serial");
7540 staticpro (&Qserial);
7541 QCbuffer = intern_c_string (":buffer");
7542 staticpro (&QCbuffer);
7543 QChost = intern_c_string (":host");
7544 staticpro (&QChost);
7545 QCservice = intern_c_string (":service");
7546 staticpro (&QCservice);
7547 QClocal = intern_c_string (":local");
7548 staticpro (&QClocal);
7549 QCremote = intern_c_string (":remote");
7550 staticpro (&QCremote);
7551 QCcoding = intern_c_string (":coding");
7552 staticpro (&QCcoding);
7553 QCserver = intern_c_string (":server");
7554 staticpro (&QCserver);
7555 QCnowait = intern_c_string (":nowait");
7556 staticpro (&QCnowait);
7557 QCsentinel = intern_c_string (":sentinel");
7558 staticpro (&QCsentinel);
7559 QClog = intern_c_string (":log");
7560 staticpro (&QClog);
7561 QCnoquery = intern_c_string (":noquery");
7562 staticpro (&QCnoquery);
7563 QCstop = intern_c_string (":stop");
7564 staticpro (&QCstop);
7565 QCoptions = intern_c_string (":options");
7566 staticpro (&QCoptions);
7567 QCplist = intern_c_string (":plist");
7568 staticpro (&QCplist);
7569
7570 Qlast_nonmenu_event = intern_c_string ("last-nonmenu-event");
7571 staticpro (&Qlast_nonmenu_event);
7572
7573 staticpro (&Vprocess_alist);
7574 #ifdef SIGCHLD
7575 staticpro (&deleted_pid_list);
7576 #endif
7577
7578 #endif /* subprocesses */
7579
7580 QCname = intern_c_string (":name");
7581 staticpro (&QCname);
7582 QCtype = intern_c_string (":type");
7583 staticpro (&QCtype);
7584
7585 Qeuid = intern_c_string ("euid");
7586 staticpro (&Qeuid);
7587 Qegid = intern_c_string ("egid");
7588 staticpro (&Qegid);
7589 Quser = intern_c_string ("user");
7590 staticpro (&Quser);
7591 Qgroup = intern_c_string ("group");
7592 staticpro (&Qgroup);
7593 Qcomm = intern_c_string ("comm");
7594 staticpro (&Qcomm);
7595 Qstate = intern_c_string ("state");
7596 staticpro (&Qstate);
7597 Qppid = intern_c_string ("ppid");
7598 staticpro (&Qppid);
7599 Qpgrp = intern_c_string ("pgrp");
7600 staticpro (&Qpgrp);
7601 Qsess = intern_c_string ("sess");
7602 staticpro (&Qsess);
7603 Qttname = intern_c_string ("ttname");
7604 staticpro (&Qttname);
7605 Qtpgid = intern_c_string ("tpgid");
7606 staticpro (&Qtpgid);
7607 Qminflt = intern_c_string ("minflt");
7608 staticpro (&Qminflt);
7609 Qmajflt = intern_c_string ("majflt");
7610 staticpro (&Qmajflt);
7611 Qcminflt = intern_c_string ("cminflt");
7612 staticpro (&Qcminflt);
7613 Qcmajflt = intern_c_string ("cmajflt");
7614 staticpro (&Qcmajflt);
7615 Qutime = intern_c_string ("utime");
7616 staticpro (&Qutime);
7617 Qstime = intern_c_string ("stime");
7618 staticpro (&Qstime);
7619 Qtime = intern_c_string ("time");
7620 staticpro (&Qtime);
7621 Qcutime = intern_c_string ("cutime");
7622 staticpro (&Qcutime);
7623 Qcstime = intern_c_string ("cstime");
7624 staticpro (&Qcstime);
7625 Qctime = intern_c_string ("ctime");
7626 staticpro (&Qctime);
7627 Qpri = intern_c_string ("pri");
7628 staticpro (&Qpri);
7629 Qnice = intern_c_string ("nice");
7630 staticpro (&Qnice);
7631 Qthcount = intern_c_string ("thcount");
7632 staticpro (&Qthcount);
7633 Qstart = intern_c_string ("start");
7634 staticpro (&Qstart);
7635 Qvsize = intern_c_string ("vsize");
7636 staticpro (&Qvsize);
7637 Qrss = intern_c_string ("rss");
7638 staticpro (&Qrss);
7639 Qetime = intern_c_string ("etime");
7640 staticpro (&Qetime);
7641 Qpcpu = intern_c_string ("pcpu");
7642 staticpro (&Qpcpu);
7643 Qpmem = intern_c_string ("pmem");
7644 staticpro (&Qpmem);
7645 Qargs = intern_c_string ("args");
7646 staticpro (&Qargs);
7647
7648 DEFVAR_BOOL ("delete-exited-processes", &delete_exited_processes,
7649 doc: /* *Non-nil means delete processes immediately when they exit.
7650 A value of nil means don't delete them until `list-processes' is run. */);
7651
7652 delete_exited_processes = 1;
7653
7654 #ifdef subprocesses
7655 DEFVAR_LISP ("process-connection-type", &Vprocess_connection_type,
7656 doc: /* Control type of device used to communicate with subprocesses.
7657 Values are nil to use a pipe, or t or `pty' to use a pty.
7658 The value has no effect if the system has no ptys or if all ptys are busy:
7659 then a pipe is used in any case.
7660 The value takes effect when `start-process' is called. */);
7661 Vprocess_connection_type = Qt;
7662
7663 #ifdef ADAPTIVE_READ_BUFFERING
7664 DEFVAR_LISP ("process-adaptive-read-buffering", &Vprocess_adaptive_read_buffering,
7665 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7666 On some systems, when Emacs reads the output from a subprocess, the output data
7667 is read in very small blocks, potentially resulting in very poor performance.
7668 This behavior can be remedied to some extent by setting this variable to a
7669 non-nil value, as it will automatically delay reading from such processes, to
7670 allow them to produce more output before Emacs tries to read it.
7671 If the value is t, the delay is reset after each write to the process; any other
7672 non-nil value means that the delay is not reset on write.
7673 The variable takes effect when `start-process' is called. */);
7674 Vprocess_adaptive_read_buffering = Qt;
7675 #endif
7676
7677 defsubr (&Sprocessp);
7678 defsubr (&Sget_process);
7679 defsubr (&Sdelete_process);
7680 defsubr (&Sprocess_status);
7681 defsubr (&Sprocess_exit_status);
7682 defsubr (&Sprocess_id);
7683 defsubr (&Sprocess_name);
7684 defsubr (&Sprocess_tty_name);
7685 defsubr (&Sprocess_command);
7686 defsubr (&Sset_process_buffer);
7687 defsubr (&Sprocess_buffer);
7688 defsubr (&Sprocess_mark);
7689 defsubr (&Sset_process_filter);
7690 defsubr (&Sprocess_filter);
7691 defsubr (&Sset_process_sentinel);
7692 defsubr (&Sprocess_sentinel);
7693 defsubr (&Sset_process_window_size);
7694 defsubr (&Sset_process_inherit_coding_system_flag);
7695 defsubr (&Sset_process_query_on_exit_flag);
7696 defsubr (&Sprocess_query_on_exit_flag);
7697 defsubr (&Sprocess_contact);
7698 defsubr (&Sprocess_plist);
7699 defsubr (&Sset_process_plist);
7700 defsubr (&Slist_processes);
7701 defsubr (&Sprocess_list);
7702 defsubr (&Sstart_process);
7703 defsubr (&Sserial_process_configure);
7704 defsubr (&Smake_serial_process);
7705 defsubr (&Sset_network_process_option);
7706 defsubr (&Smake_network_process);
7707 defsubr (&Sformat_network_address);
7708 #if defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H)
7709 #ifdef SIOCGIFCONF
7710 defsubr (&Snetwork_interface_list);
7711 #endif
7712 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
7713 defsubr (&Snetwork_interface_info);
7714 #endif
7715 #endif /* defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H) */
7716 #ifdef DATAGRAM_SOCKETS
7717 defsubr (&Sprocess_datagram_address);
7718 defsubr (&Sset_process_datagram_address);
7719 #endif
7720 defsubr (&Saccept_process_output);
7721 defsubr (&Sprocess_send_region);
7722 defsubr (&Sprocess_send_string);
7723 defsubr (&Sinterrupt_process);
7724 defsubr (&Skill_process);
7725 defsubr (&Squit_process);
7726 defsubr (&Sstop_process);
7727 defsubr (&Scontinue_process);
7728 defsubr (&Sprocess_running_child_p);
7729 defsubr (&Sprocess_send_eof);
7730 defsubr (&Ssignal_process);
7731 defsubr (&Swaiting_for_user_input_p);
7732 defsubr (&Sprocess_type);
7733 defsubr (&Sset_process_coding_system);
7734 defsubr (&Sprocess_coding_system);
7735 defsubr (&Sset_process_filter_multibyte);
7736 defsubr (&Sprocess_filter_multibyte_p);
7737
7738 #endif /* subprocesses */
7739
7740 defsubr (&Sget_buffer_process);
7741 defsubr (&Sprocess_inherit_coding_system_flag);
7742 defsubr (&Slist_system_processes);
7743 defsubr (&Sprocess_attributes);
7744 }
7745
7746 /* arch-tag: 3706c011-7b9a-4117-bd4f-59e7f701a4c4
7747 (do not change this comment) */